public class JdbcTest {
@Test
public void test() {
Connection conn = null;
Statement stmt = null;
try {
// STEP 1: 连接数据库
// JDBC driver name and database URL
String JDBC_DRIVER = "org.h2.Driver";
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
String DB_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
// Database credentials
String USER = "sa";
String PASS = "";
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 2: 设置参数,查询
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
//STEP 4: 处理查询结果
String insertSql = "insert into REGISTRATION (id, first, last, age) values (?, ?, ?, ?)";
PreparedStatement insertPreparedStatement = conn.prepareStatement(insertSql);
insertPreparedStatement.setInt(1, 1);
insertPreparedStatement.setString(2, "1");
insertPreparedStatement.setString(3, "1");
insertPreparedStatement.setInt(4, 1);
insertPreparedStatement.executeUpdate();
String querySql = "select * from REGISTRATION";
ResultSet resultSet = stmt.executeQuery(querySql);
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
Registration registration = new Registration();
registration.setId(resultSet.getInt(metaData.getColumnName(1)));
registration.setFirst(resultSet.getString(metaData.getColumnName(2)));
registration.setLast(resultSet.getString(metaData.getColumnName(3)));
registration.setAge(resultSet.getInt(metaData.getColumnName(4)));
System.out.println(registration);
}
// STEP 4: 关闭连接
stmt.close();
conn.close();
} catch(Exception se) {
......
} //end try
System.out.println("Goodbye!");
}
@Data
static class Registration {
private int id;
private String first;
private String last;
private int age;
}
}
评论