· 10 years ago · Sep 08, 2016, 03:20 PM
1import java.sql.*;
2
3public class DatabaseUtil {
4
5 private static final String DATABASE_URL = "jdbc:hsqldb:mem";
6 private static final String USER = "sa";
7 private static final String PASSWORD = "pwd";
8
9 public static Connection getConnection() throws SQLException {
10 return DriverManager.getConnection(DATABASE_URL, USER, PASSWORD);
11 }
12
13 static void startEmbeddedDatabase() throws Exception {
14 //do not let hsqldb reconfigure java.util.logging used by easy batch
15 System.setProperty("hsqldb.reconfig_logging", "false");
16 createPeopleTable();
17 }
18
19 public static void createPeopleTable() throws Exception {
20 Connection connection = getConnection();
21 Statement statement = connection.createStatement();
22
23 String query = "DROP TABLE IF EXISTS people";
24 statement.executeUpdate(query);
25 query = "CREATE TABLE people (\n" +
26 " id BIGINT IDENTITY NOT NULL PRIMARY KEY,\n" +
27 " firstName VARCHAR(20),\n" +
28 " lastName VARCHAR(20)\n" +
29 ");";
30
31 statement.executeUpdate(query);
32 statement.close();
33 connection.close();
34 }
35
36 public static void dumpPeopleTable() throws Exception {
37 System.out.println("Loading people from the database...");
38 Connection connection = getConnection();
39 Statement statement = connection.createStatement();
40 ResultSet resultSet = statement.executeQuery("select * from people");
41
42 while (resultSet.next()) {
43 System.out.println(
44 "Person : firstName= " + resultSet.getString("firstName") + " | " +
45 "lastName= " + resultSet.getString("lastName")
46 );
47 }
48
49 resultSet.close();
50 statement.close();
51 connection.close();
52 }
53
54}