I am writing a desktop app in java to add/display employees.I thought of using hsqldb.I created the program as below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HSQLDBManualOp {
/**
* @param args
*/
public static void main(String[] args) {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
String createtablestr = "CREATE TABLE employeedetails (EMPNAME varchar(20));";
String insertstr1 = "INSERT INTO employeedetails (EMPNAME) VALUES ('EMPNAME1')";
String insertstr2 = "INSERT INTO employeedetails (EMPNAME) VALUES ('EMPNAME2')";
String insertstr3 = "INSERT INTO employeedetails (EMPNAME) VALUES ('EMPNAME3')";
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection = DriverManager.getConnection("jdbc:hsqldb:file:C:/code/java/march112011aDB", "SA", "");
} catch (SQLException e) {
e.printStackTrace();
}
if (connection == null){
System.out.println(" connection null");
return;
}
try {
statement = connection.createStatement();
statement.executeUpdate(createtablestr);
statement.executeUpdate(insertstr1);
statement.executeUpdate(insertstr2);
statement.executeUpdate(insertstr3);
resultSet = statement.executeQuery("SELECT EMPNAME FROM EMPLOYEEDETAILS");
} catch (SQLException e) {
e.printStackTrace();
}
try {
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:" + resultSet.getString("EMPNAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
when I ran the program ,I got the output
EMPLOYEE NAME:EMPNAME1
EMPLOYEE NAME:EMPNAME2
EMPLOYEE NAME:EMPNAME3
Then I changed the insert statements to add EMPNAME4,EMPNAME5,EMPNAME6
I expected it to print employees 1,2,3,4,5,6 but when I ran the code,I got only the new values.
EMPLOYEE NAME:EMPNAME4
EMPLOYEE NAME:EMPNAME5
EMPLOYEE NAME:EMPNAME6
Is it not possible to persist the values when using jdbc:hsqldb:file ? I also would like to check if the table already exists..and execute the create table statement only if the table does not exist.Can anyone tell me how to do this?
Or do I have to use server mode?If so how do I create db from within the program?
please help..this is my first attempt at jdbc/hsqldb..
thanks,
mark