1、JDK自带的数据库 - Derby
一句话概括:JDK6之后自带的微型数据库。默认安装之后会放在jdk下面的db包中,如果没有,可以自行下载:http://db.apache.org/derby/derby_downloads.html
JDK 6 的程序员们也许会发现,除了传统的 bin、jre 等目录,JDK 6 新增了一个名为 db 的目录。这便是 Java 6 的新成员:Java DB。这是一个纯 Java 实现、开源的数据库管理系统(DBMS),源于 Apache 软件基金会(ASF)名下的项目 Derby。它只有 2MB 大小,对比动辄上 G 的数据库来说可谓袖珍。特别适合Java的单元测试和集成测试之中。
2、Derby使用
(1)加入pom依赖
- <dependency>
- <groupId>org.apache.derby</groupId>
- <artifactId>derby</artifactId>
- <version>10.6.1.0</version>
- <scope>test</scope>
- </dependency>
(2)创建数据库、连接、操作、销毁数据库、关闭
- try { // load the driver
- Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
- System.out.println("Load the embedded driver");
- Connection conn = null;
- Properties props = new Properties();
- props.put("user", "user1"); props.put("password", "user1");
- //create and connect the database named helloDB
- conn=DriverManager.getConnection("jdbc:derby:helloDB;create=true", props);
- System.out.println("create and connect to helloDB");
- conn.setAutoCommit(false);
- // create a table and insert two records
- Statement s = conn.createStatement();
- s.execute("create table hellotable(name varchar(40), score int)");
- System.out.println("Created table hellotable");
- s.execute("insert into hellotable values('Ruth Cao', 86)");
- s.execute("insert into hellotable values ('Flora Shi', 92)");
- // list the two records
- ResultSet rs = s.executeQuery(
- "SELECT name, score FROM hellotable ORDER BY score");
- System.out.println("name\t\tscore");
- while(rs.next()) {
- StringBuilder builder = new StringBuilder(rs.getString(1));
- builder.append("\t");
- builder.append(rs.getInt(2));
- System.out.println(builder.toString());
- }
- // delete the table
- s.execute("drop table hellotable");
- System.out.println("Dropped table hellotable");
- rs.close();
- s.close();
- System.out.println("Closed result set and statement");
- conn.commit();
- conn.close();
- System.out.println("Committed transaction and closed connection");
- try { // perform a clean shutdown
- DriverManager.getConnection("jdbc:derby:;shutdown=true");
- } catch (SQLException se) {
- System.out.println("Database shut down normally");
- }
- } catch (Throwable e) {
- // handle the exception
- }
- System.out.println("SimpleApp finished");
3、应用场景
单元测试、自动化集成测试
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/515281,如需转载请自行联系原作者