Running method continiously inside Main - java

I have two integers; start and stop
Initially start is 0 and stop is 1. Once the user closes the window start becomes 1.
I have a method which updates my JTable;
private void Update_table(){
try{
String sql ="select * from orders ";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
Table_Employee.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
I want to update the table continuously but When I put a while loop inside the void main method the program crashes;
void main;
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//Update_table();
while(start<stop)
new Employee_info().Update_table();
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Employee_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Employee_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Employee_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Employee_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Employee_info().setVisible(true);
// while(1<2)
// rh.Update_table();
// Update_table();
}
});
}
The erro;
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException: User 12345 already has more than 'max_user_connections' active connections
Where 12345 is the user name to connect to the database, is it because I login to the database in different classes and run queries as well?
connection class;
import java.sql.*;
import javax.swing.*;
public class javaconnect {
Connection conn=null;
public static Connection ConnecrDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://XXX.com:3306/XXX_pizza","12345 ","XXXX");
// JOptionPane.showMessageDialog(null, "You got connected");
return conn;
}catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
The Employee_Info class calls to javaconnect class to make a connection;
public Employee_info() {
initComponents();
conn=javaconnect.ConnecrDb();
Update_table();
}

There are a couple things:
1) In a while loop like that, you should probably call Thread.sleep() at some point.
2) In this case, because you're not sleeping and getting a new connection every time you call the Employee_info constructor, you're creating lots of connections, that's likely the direct cause of your error.
3) You shouldn't have a business object like Employee_info make the connection. Instead, you should have a tier in between (usually called a data access layer), with something like this:
public class EmployeeDao {
public Employee_info getEmployeeInfo(){
Connection conn = getConnection();
//do something with the connection, construct employee info
return employeeInfo
}
}
4) You should use a connection pool, instead of instantiating connections by hand. Commons-dbcp is a used, erm, commonly.
5) Follow Java naming conventions.

Related

Null pointer exception while execution a jdbc code in net beans? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i m connecting ms access to odbc and odbc to javacode.
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author aditya
*/
public class Odbc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con=null;Statement st=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
}
try {
con=DriverManager.getConnection("jdbc:odbc:studentdsn");
} catch (SQLException ex) {
Logger.getLogger(Odbc.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Statement St = con.createStatement();
String sql="insert into Student values(111,gfhgf,kjhk,123,jgfj)";
int n;
n=st.executeUpdate(sql);
here.. i m getting runtime error. deferencing null pointer.
} catch (SQLException ex) {
System.out.println(ex);
}
}
}
You have two Statement type variables. One which you defined as null:
Statement st=null;
and one which was actually initialized ("s" is uppercase here):
Statement St = con.createStatement();
then you are calling a function on the null variable:
n=st.executeUpdate(sql);
You have defined con as null and then you try to initialize it like:
try {
con=DriverManager.getConnection("jdbc:odbc:studentdsn");
} catch (SQLException ex) {
Logger.getLogger(Odbc.class.getName()).log(Level.SEVERE, null, ex);
}
Now if you get exception while creating connection, your connection would still be null and then you try to use null connection to create statement as below:
try {
Statement St = con.createStatement();
And hence null pointer exception.
Create all the JDBC connection related statement in one try catch block and most importantly find out why connection creation failed.

Java .jar file can't receive socket message

I am trying to create a server and client(s) app, where the server can send messages to the client(s), and the client(s) can only accept the messages from the server.
I have succeed this goal. The problem is, that the client.jar won't receive any messages from the server. But everything work just fine in netbean.
Any idea why this happen ?
Here's my complete server code :
public sServerUI() {
super("Server : "+System.getenv("COMPUTERNAME")); // mendapatkan nama komputer
initComponents();
}
public void startListener(){
Random randomGen = new Random();
try{
myPort = randomGen.nextInt(9999);
server = new ServerSocket(myPort);//Bebas portnya, tp nggk boleh sudah terpakai atau pakai random jg bisa
btnListen.setEnabled(false);
while(key == null) {
key = JOptionPane.showInputDialog(this, "Input your Key : ", "Insert Key", JOptionPane.PLAIN_MESSAGE);
}
if(key.equals("")) {
key = "Random";
txtMessage.setText(txtMessage.getText()+"Invalid key inputted, key automatically set to '"+key+"'\n");
} else txtMessage.setText(txtMessage.getText()+"Key set to '"+key+"'\n");
} catch (IOException e) {//Kalau sudah terpakai muncul error
JOptionPane.showMessageDialog(this, "Could not listen at " + myPort);
//Gagal, keluarin info
} finally{
myPort = server.getLocalPort();
lblPort.setText("Port: "+myPort);
System.out.println("Port: "+myPort);
}
acceptClient.start();
}
public void windowClosing(WindowEvent e){
try {
server.close();
for (int i=0;i<numberOfClient;i++){
socketIn[i].close();
socketOut[i].close();
}
} catch (IOException ex) {
System.out.println("Error "+ex.getMessage());
}
}
class Accepter extends Thread{
#Override
public void run(){
while (true){
try{
client[numberOfClient] = server.accept();
numberOfClient++;
lblStatus.setText("Status: "+numberOfClient+" client(s) connected");
Handler handleClient = new Handler(numberOfClient-1);
handleClient.start();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Accept failed: " + myPort);
}
}
}
}
class Handler extends Thread{
private int arr;
Handler(int ar){
arr = ar;
try{
socketIn[arr] = new BufferedReader(new InputStreamReader(client[arr].getInputStream()));
socketOut[arr] = new PrintWriter(client[arr].getOutputStream(), true);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Read failed");
}
}
#Override
public void run(){
while (true){
try{
if (socketIn[arr].ready()){
System.out.println("Reading...");
line = socketIn[arr].readLine();
if (!txtMessage.getText().equals("")){
txtMessage.setText(txtMessage.getText()+"\n");
//broadcast message ke client2 lain
}
txtMessage.setText(txtMessage.getText()+"Client "+(arr+1)+": "+line);
for (int i=0;i<numberOfClient;i++){
if (i!=arr){//jgn kembaliin ke client yg kirim
socketOut[i].println("Client "+(arr+1)+": "+line);
}
}
}
} catch (IOException e) {
System.out.println("Read failed");
}
}
}
}
private void btnListenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
startListener();
}
private void sendData(String data) {
for (int j=0;j<numberOfClient;j++){
socketOut[j].println(data);
}
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(numberOfClient > 0) {
int packetIndex = 1;
String ext = getExt(filePath, '.');
String sData = "start"+pemisahString+fByte.length+pemisahString+ext+pemisahString; //menaruh kata kunci 'start' dan ukuran file di awal message, serta extensionnya
sendData(sData);
sData = "";
int k = 0;
for(int i = 0; i < fByte.length; i++) {
if(k >= Math.ceil((double)fByte.length/10.0)) {
k = 0;
sData = rc4(key, sData);
sendData(Integer.toString(packetIndex)+pemisahString+sData);
txtMessage.setText(txtMessage.getText()+"packet-"+packetIndex+" sent ! isi : "+revertToString(rc4(key,revertToString(sData)))+"\n");
packetIndex++;
sData = "";
}
sData += fByte[i];
sData += pemisahString;
k++;
if(i == fByte.length-1) {
sData = rc4(key, sData);
sendData(Integer.toString(packetIndex)+pemisahString+sData);
txtMessage.setText(txtMessage.getText()+"packet-"+packetIndex+" sent ! isi : "+revertToString(rc4(key,revertToString(sData)))+"\n");
packetIndex++;
sData = "";
}
}
sData = "end"+pemisahString;
sendData(sData);
txtMessage.setText(txtMessage.getText() + "Done ! divided into "+k+" piece(s) per packet\n");
} else JOptionPane.showMessageDialog(this, "No Client Connected !", "Error", JOptionPane.ERROR_MESSAGE);
}
private void fileBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("d:/Kul/Smstr 6/Kripto n Steno/Stream Cipher/"));
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
filePath = chooser.getSelectedFile().getPath();
try {
inputFile = new File(filePath);
fIn = new FileInputStream(inputFile);
fByte = new byte[(int)inputFile.length()];
System.out.println("file size : "+(int)inputFile.length()+" byte(s)");
System.out.print("Isi file : ");
fIn.read(fByte);
fIn.close();
for(int i = 0; i < fByte.length; i ++) {
System.out.print(fByte[i]+" ");
}
System.out.print("end of file\n");
String stringBuatDitampilin = getExt(filePath, (char)92);
txtMessage.setText(txtMessage.getText() + "'" + stringBuatDitampilin + "' Loaded !\n");
btnSend.setEnabled(true);
//fIn.close();
//JOptionPane.showMessageDialog(this, "File Loaded !", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch(java.io.IOException e) {
JOptionPane.showMessageDialog(this, e.toString(), "IO Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(sServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new sServerUI().setVisible(true);
}
});
}
and here's my complete client code :
public sClientUI() {
super("Client");
initComponents();
}
public void listenSocket(){
//Create socket connection
try{
socket = new Socket(txtHost.getText(), Integer.parseInt(txtPort.getText()));
socketOut = new PrintWriter(socket.getOutputStream(), true);
socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
txtMessage.setText(txtMessage.getText()+"Succesfully connected to "+txtHost.getText()+" !\n");
while(key == null) {
key = JOptionPane.showInputDialog(this, "Input your Key : ", "Insert Key", JOptionPane.PLAIN_MESSAGE);
}
if(key.equals("")) {
key = "Random";
txtMessage.setText(txtMessage.getText()+"Invalid key inputted, key automatically set to '"+key+"'\n");
} else txtMessage.setText(txtMessage.getText()+"Key set to '"+key+"'\n");
txtHost.setEditable(false);
txtPort.setEditable(false);
btnConnect.setEnabled(false);
myListener = new Timer(250, readLine);
myListener.start();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(this, "Unknown host: "+e.getMessage(), "Unknown Hostname", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Either your hostname is wrong, or you entered wrong port number\n"+e.getMessage(),"Input Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, e.getMessage(),"Invalid Port Number", JOptionPane.ERROR_MESSAGE);
}
}
public void windowClosing(WindowEvent e){
try {
socket.close();
socketIn.close();
socketOut.close();
} catch (IOException ex) {
System.out.println("Error "+ex.getMessage());
}
}
ActionListener readLine = new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
try{
if (socketIn.ready()){
String tempReceiver;
if((tempReceiver = socketIn.readLine()) != null) {
exStr(tempReceiver); //untuk memotong-motong string dan meng-create file baru
}
}
} catch (IOException e) {
System.out.println("Read failed");
}
}
};
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
listenSocket();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(sClientUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new sClientUI().setVisible(true);
}
});
}
the .jar client and server has been connected to each other, they just can't send or receive any messages
Your code is missing some important peaces. For example the imports. They show us what libraries you used and give us chances to do some reserches.
1) For example the line:
myListener = new Timer(250, readLine);
It can't be java.util.Timer because this class doesn't have an constructor (long/int, ActionListener). Possibly this call only runs once instead of multiple times, but I'm unable to know and tell you that.
2) Another example: You have the line
acceptClient.start();
I can only assume that there is an instance variable
Accepter acceptClient = new Accepter();
but it can also refer to a completely different class which works differently.
3) Back to my first example:
You are doing some kind of polling. This is not good style in java because Java Thready are by design optimized for blocking threads. Use a code block like this instead (untested; inspired by your server code)
class ClientThread extends Thread{
#Override
public void run(){
try{
String tempReceiver;
while ((tempReceiver = socketIn.readLine()) != null) {
exStr(tempReceiver);
}
} catch (IOException e) {
System.out.println("Read failed");
}
}
}
In this case you don't need polling and you have immediate response. This consumes less CPU.
A completely different option would be to use Java NIO, which is more optimized for single-thread applications (or let's call it few-thread).
Some off-topic remarks:
OT 1)
Calling Swing-functions like JOptionPane.showMessageDialog() and setText() is dangerous from threads. Swing itself is not Thread-safe. You should use a EventQueue.invokeLater() wrapper around it. my favourite: SwingUtils.invokeLater()
OT 2)
Having the variable tempReceiver class-global (I assume this because I can't see any declaration) is also dangerous because you likely use it somewhere else and possibly exactly overwrite it during the readLine() and exStr() calls in the other thread (if Timer is the Swing-implementation, it runs an extra thread).
OT 3)
You are saying "the .jar client and server has been connected to each other". Does this mean you have two open console windows with a java -jar command running in each window? If not, you might miss some important console output (possibly exceptions).
The windows distribution of java has 2 java runners: javaw.exe which is called when double-clicking a .jar file in the Explorer. And java.exe which also runs your program but also opens a console window which shows the output of System.out.println etc. This console is very important for debugging. It shows the same output as the Debug window in NetBeans or Eclipse.
Solved
it was because i encrypt the message using some cipher algorithm
and i send the bytes as string
some ciphered character are unreadable by the console, and so the program can't do certain key operations to process the message
thanks all anyway :)

Adding custom Look & Feel using Netbeans

I need a bit of help. I'm experimenting with Java L&Fs, and I have absolutely no idea how to get Netbeans to actually change the look and feel. I'm using the Synthetica Blue Ice L&F, and in the coding where NetBeans has the Nimbus LF coding, I've commented out the Nimbus set and this is what I inserted (extract from original coding):
import de.javasoft.plaf.synthetica.SyntheticaBlueIceLookAndFeel;
import javax.swing.*;
import java.awt.*;
public MainMenu() {
initComponents();
try {
UIManager.addAuxiliaryLookAndFeel(new SyntheticaBlueIceLookAndFeel());
UIManager.setLookAndFeel(new SyntheticaBlueIceLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
}
Where NetBeans inserts its own Look and Feel coding, I've commented it out and it looks like this:
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
UIManager.addAuxiliaryLookAndFeel(new SyntheticaBlueIceLookAndFeel());
UIManager.setLookAndFeel(new SyntheticaBlueIceLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// JOptionPane.showMessageDialog(null, info.getClassName());
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// }
// catch (Exception e){
// java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
// }
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainMenu().setVisible(true);
}
});
}
Yet, when I run the application, it still looks the same as the default LF. I've run a script to check and see what LFs I have installed, and this is what I got:
javax.swing.plaf.metal.MetalLookAndFeel
javax.swing.plaf.nimbus.NimbusLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel
I've noticed that there's a Look and Feel tab in the design palette. Why isn't Synthetica showing there?
Seems you need to call UIManager.addAuxiliaryLookAndFeel(LookAndFeel)1 before trying to use it.
Adds a LookAndFeel to the list of auxiliary look and feels. The auxiliary look and feels tell the multiplexing look and feel what other LookAndFeel classes for a component instance are to be used in addition to the default LookAndFeel class when creating a multiplexing UI. The change will only take effect when a new UI class is created or when the default look and feel is changed on a component instance.

Datasource error when migrating from Tomcat server to JBoss?

I would appreciate if anyone can help me out here. I have developed an application using Apache Tomcat and it is deployed and working. However when I wanted to migrate the app to JBoss and deploy the WAR file on that server, I got a datasource error. I'm new to JBoss and I have no clue on what should I do next to solve this issue. I would appreciate if someone could guide me through this process!
My DBConnector class code:
import java.sql.*;
import java.util.Properties;
import java.io.InputStream;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory;
public class DbConnector {
private static String JDBC_DRIVER = "jdbc.driver";
private static String JDBC_URL = "jdbc.url";
private static String JDBC_USER = "jdbc.user";
private static String JDBC_PASSWORD = "jdbc.password";
private static Properties props = new Properties();
private Connection connection = null;
private Statement stat = null;
private ResultSet rs = null;
private static volatile DataSource dsObj;
static {
try {
// a way to retrieve the data in
// connection.properties found
// in WEB-INF/classes
InputStream is = DbConnector.class.getResourceAsStream("/connection.properties");
props.load(is);
//PropertyConfigurator.configure("log4j.properties");
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName(props.getProperty(JDBC_DRIVER)).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initialize() {
try {
dsObj = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Constructor
*/
public DbConnector() {
try {
initialize();
this.connection = getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns DB Connection
* #return Connection
* #throws SQLException
*/
public static Connection getConnectionFromPool() throws SQLException {
Connection connection = null;
// checking for null singleton instance
if (null == dsObj) { // synchronized over class to make thread safe
synchronized (DbConnector.class) {
// double checking for making singleton instance thread safe
if (null == dsObj) {
initialize();
}
}
}
// getting connection from data sourceconnection = dsObj.getConnection();
return connection;
}
/**
* Get Connection
* #return Connection object
* #throws SQLException
*/
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(props.getProperty(JDBC_URL), props.getProperty(JDBC_USER), props.getProperty(JDBC_PASSWORD));
}
/**
* Execute Query
* Purpose: SELECT
* #param sql SQL Statement
* #return ResultSet
*/
public ResultSet executeQuery(String sql) {
try {
if (connection == null) {
return null;
}
stat = connection.createStatement();
rs = stat.executeQuery(sql);
return rs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Execute Update
* Purpose: Insert, Update, Delete
* #param sql SQL Statement
* #return int No. of Rows Updated
*/
public int executeUpdate(String sql) {
try {
if (connection == null) {
return -1;
}
stat = connection.createStatement();
return stat.executeUpdate(sql);
} catch (Exception e) {
//e.printStackTrace();
return -1;
}
}
/**
* Execute
* Purpose: Create, Drop
* #param sql statement to update.
* #return true is statement execute sucessfuly and false otherwise
*/
public boolean execute(String sql) {
try {
if (connection == null) {
return false;
}
stat = connection.createStatement();
return stat.execute(sql);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
/**
* Close ResultSet
*/
public void closeResultSet() {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
/**
* Close Statement
*/
public void closeStatement() {
if (stat != null) {
try {
stat.close();
} catch (Exception e) {
e.printStackTrace();
//log.error(e);
}
}
}
/**
* Close Connection
*/
public void closeConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Close
* Connection, Statement and Resultset *
*/
public void close() {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After reading about this online, I know I have to do something to the context.xml and web.xml files.
Would someone show me some sample code or give me some assistance with this please?
The first thing I do is get rid of your own connection pool code and use the one provided by the container. You basically define the DataSource and the container (Tomcat/JBOSS) will make it available to your application via JNDI. Once defined, you can refer to it in your web.xml. Search google for how-to.
<resource-ref>
<description>Customer Database</description>
<res-ref-name>jdbc/CustomerDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
UPDATE
If you still want to make this work your way, then make sure you have the jar file containing the org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory in your classpath (WEB-INF/lib). And post the stacktrace you are getting.
UPDATE 2
The error is very clear
Web mapping already exists for deployment URL file:/C:/Users/Dane/Desktop/jboss-as-distribution-6.0.0.Final/jboss-6.0.0.Final/server/default/tmp/vfs/automountec9d6360903186ac/SurveyApplication.war-a018e9cb945f462b/
Seems like you already have another application deployed with the same context path.

unable to drop table in HSQLDB

I am unable to drop table with default user SA(or any user for that matter) in HSQLDB even though I can create table and read them without problem, please see my code below, what's wrong?
On the other hand, If I use a third party SQL client(eg. squirrel), I can login and drop table without problem even when user is empty.
public static void main(String[]args){
try {
DBManager.executeUpdate("drop table mytable");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public static Connection getConnection(){
Connection c =null;
try {
c = DriverManager.getConnection("jdbc:hsqldb:file:e:\\xxx_db\\xxx", "SA", "");
} catch (SQLException ex) {
ex.printStackTrace();
}
return c;
}
public static int executeUpdate(String s) throws SQLException {
Connection con = getConnection();
try{
return con.createStatement().executeUpdate(s);
}
finally{
if(con!=null)try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
It turns out I need to do an explicit shutdown aftwards
DBManager.executeUpdate("shutdown");
Try committing after executing the DDL.

Categories