I'm trying to build some kind of Unit test for DB connection. First I'm creating a new connection and new table, populate it and then check if the data exists, all good at this point. than a client create a new connection and tries to get the same data but the query result is empty, 0 rows, 2 columns.
public class H2dbTest {
private static final String CREATE_TABLE = "CREATE TABLE TEST(ID varchar(12) primary key, NAME char(7))";
private static final String INSERT_QUERY = "INSERT INTO TEST(ID, NAME) VALUES (1234567,'TEST')";
private static final String SELECT_QUERY = "SELECT ID, NAME FROM TEST";
public static void main(String[] args) {
DeleteDbFiles.execute("~", "test", true);
Connection connection = getDBConnection();
insertWithStatement(connection);
readFromClient();
}
private static void insertWithStatement(Connection connection) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
stmt.execute(CREATE_TABLE);
stmt.execute(INSERT_QUERY);
ResultSet rs = stmt.executeQuery(SELECT_QUERY);
System.out.println("Check DB after insert");
while (rs.next()) {
System.out.println("Id " + rs.getInt("ID") + " Name " + rs.getString("NAME"));
}
stmt.closeOnCompletion();
} catch (SQLException e) {
System.out.println("Exception Message " + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readFromClient(){
Connection connection = null;
try {
connection = getDBConnection();
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(SELECT_QUERY);
System.out.println("Client DB query result");
while (rs.next()) {
System.out.println("Id " + rs.getInt("ID") + " Name " + rs.getString("ID"));
}
} catch (SQLException e) {
System.out.println("Exception Message " + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
i was missing connection.commit();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.