重點技術-20181003-記憶體資料庫Derby
Derby是純JAVA的可內嵌資料庫,優點在於,不需要安裝資料庫。
------------------Maven設定------------------ <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.5.3.0</version> </dependency>
------------------程式碼使用------------------
private static String driverEmbeddedDriver = "org.apache.derby.jdbc.EmbeddedDriver";//本地嵌入式驅動 private static String driverClientDriver = "org.apache.derby.jdbc.ClientDriver";//網路連線式驅動 private static String protocolDiskMode = "jdbc:derby:D:\\Java\\firstdb";//磁碟模式 private static String protocolMemoryMode = "jdbc:derby:memory:firstdb";//記憶體模式
public void doIt() { Connection connection = null; Statement statement = null; ResultSet resultSet = null; //建立資料庫連線 try { connection = DriverManager.getConnection(protocolDiskMode + ";create=true;upgrade=true"); } catch (SQLException e) { e.printStackTrace(); } try { statement = connection.createStatement(); long start = System.currentTimeMillis(); long end = 0L; //建立表 // statement.execute("drop table firsttable"); // statement.execute("create table firsttable(itemNumber INT NOT NULL,vendorName CHAR(64))"); // end = System.currentTimeMillis(); // System.out.println("創表用時:" + (end - start));//100-115ms,硬碟模式用時247ms // start = end; // // //插入資料 // statement.execute("INSERT INTO FIRSTTABLE VALUES (10,'TEN'),(20,'TWENTY'),(30,'THIRTY')"); // for (int i = 0; i < 10000; i++) // { // statement.execute("INSERT INTO FIRSTTABLE VALUES (" + i + ",'value" + i + "')"); // } // end = System.currentTimeMillis(); // System.out.println("插入用時:" + (end - start));//記憶體模式用時18-20s,硬碟模式用時20-22s // start = end; //讀取資料 resultSet = statement.executeQuery("select * from firsttable where vendorName like 'value%'"); // while (resultSet.next()) // { // System.out.println(resultSet.getInt(1)); // System.out.println(resultSet.getString(2)); // } end = System.currentTimeMillis(); System.out.println("查詢用時:" + (end - start));//記憶體模式用時50-60ms,磁碟模式用時(剛插入的資料50-80ms,下次重新從硬碟載入讀取用時200-230ms) start = end; } catch (SQLException e1) { e1.printStackTrace(); } try { connection.close(); connection = null; statement.close(); statement = null; resultSet.close(); resultSet = null; } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { TestDerby derby = new TestDerby(); derby.doIt(); }