public class DBConnector {
private Connection conn;
public DBConnector() {
final String driver = "org.apache.derby.jdbc.EmbeddedDriver";
final String connectionURL = "jdbc:derby:DBConnector;create=true";
try {
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Boolean createTables() {
String createString = "CREATE TABLE personen (name VARCHAR(64) NOT NULL, "
+ "vorname VARCHAR(64) NOT NULL,"
+ "adresse VARCHAR(64) NOT NULL,"
+ "PRIMARY KEY(name, vorname))";
if (!existsTable("personen")) {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(createString);
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
try {
stmt.close();
} catch (SQLException e1) {
}
return false;
}
}
return true;
}
public Boolean dropTables() {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE personen");
stmt.close();
return true;
} catch (SQLException e) {
try {
stmt.close();
} catch (SQLException e1) {
}
return false;
}
}
public Boolean existsTable(String tableName) {
final String sqlString = "SELECT TABLENAME FROM SYS.SYSTABLES WHERE TABLETYPE='T'";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlString);
while (rs.next()) {
String actValue = rs.getString(1);
if (actValue.equalsIgnoreCase(tableName)) {
rs.close();
stmt.close();
return true;
}
}
rs.close();
stmt.close();
return false;
} catch (SQLException e) {
try {
rs.close();
stmt.close();
} catch (SQLException e1) {
}
return null;
}
}
public List<Person> getAllPersons() {
ArrayList<Person> result = new ArrayList<Person>();
final String sqlString = "SELECT name,vorname,adresse FROM personen";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlString);
while (rs.next()) {
result.add(new Person(rs.getString(1), rs.getString(2), rs
.getString(3)));
}
rs.close();
stmt.close();
return result;
} catch (SQLException e) {
try {
rs.close();
stmt.close();
return null;
} catch (SQLException e1) {
}
}
return null;
}
public void addPerson(Person person) {
final String sqlString = "INSERT INTO personen VALUES (?,?,?)";
PreparedStatement psInsert = null;
try {
psInsert = conn.prepareStatement(sqlString);
psInsert.setString(1, person.getName());
psInsert.setString(2, person.getVorname());
psInsert.setString(3, person.getAdresse());
psInsert.executeUpdate();
psInsert.close();
} catch (SQLException e) {
try {
psInsert.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
conn.close();
super.finalize();
}
}