- CREATE
- ALTER
- DROP
這次Mix使用HSQLDB所提供的JDBC Driver,連接到Database,來使用DDL操作,進行建立Table,修改Table等動作。

導入JDBC Driver到專案中。
- 官網下載: http://hsqldb.org/
- hsqldb.jar導入到專案中。
- 或使用 Maven Reponsitory,選擇版本後,在 pom.xml貼上:
<dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.10</version> </dependency>

首先,Mix先建立1條連線,測試是否能連線到Database,預設port:9001。
/** * Connection. */ @Test public void connection() { Connection conn = null; try { Class.forName("org.hsqldb.jdbcDriver"); conn = DriverManager.getConnection( "jdbc:hsqldb:hsql://localhost:9001/openyu_java" , "SA", ""); // System.out.println(conn); assertTrue(conn != null); } catch (Exception ex) { ex.printStackTrace(); } finally { if (conn != null) { try { // release conn.close(); } catch (Exception ex) { } } } }
console查看其結果。
org.hsqldb.jdbc.JDBCConnection@19d009b4

連線Database成功後,Mix建立了以下方法,主要是建立連線與釋放資源,為了方便測試時的調用。
/** * Creates the connection. * * @return the connection */ protected Connection createConnection() { Connection result = null; try { Class.forName("org.hsqldb.jdbcDriver"); result = DriverManager.getConnection( "jdbc:hsqldb:hsql://localhost:9001/openyu_java" , "SA", ""); } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * Close connection. * * @param conn * the conn */ protected void closeConnection(Connection conn) { try { if (conn != null) { conn.close(); } } catch (Exception ex) { } } /** * Close statement. * * @param stmt * the stmt */ protected void closeStatement(Statement stmt) { try { if (stmt != null) { stmt.close(); } } catch (Exception ex) { } } /** * Close result set. * * @param rs * the rs */ protected void closeResultSet(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (Exception ex) { } }

接著建立Table:Magazine ,只有3個屬性,分別是:
- id:唯一識別碼。
- name:名稱。
- price:價格。
/** * Creates the table. */ @Test public void createTable() { Connection conn = null; Statement stmt = null; try { conn = createConnection(); stmt = conn.createStatement(); // System.out.println(stmt); assertTrue(stmt != null); String SQL = "CREATE TABLE magazine (" + " id bigint not null," + " name varchar(100)," + " price int," + " PRIMARY KEY (id)" + " );"; stmt.executeUpdate(SQL); } catch (Exception ex) { ex.printStackTrace(); } finally { // close closeStatement(stmt); closeConnection(conn); } }
測試成功後,可以用GUI查看HSQLDB內的Table,一共有3個Column被成功建立。
沒有留言:
張貼留言