Gradle构建H2数据库示例
H2数据库是Java实现的轻量级数据库, 可以运行在内存中. 下面的例子展示如何用Gradle构建H2数据库.
第一步 建立Gradle项目
第二步 在Gradle脚本中添加H2数据库依赖
使用的版本是1.3.148
dependencies { compile group: 'commons-collections', name: 'commons-collections', version: '3.2' testCompile group: 'junit', name: 'junit', version: '4.+' compile group: 'com.h2database', name: 'h2', version: '1.3.148' }
第三步 连接到数据库
H2数据库的JDBC驱动是自带的, 类名是org.h2.Driver
Connection conn = null; Statement stmt = null; Class.forName("org.h2.Driver"); conn = DriverManager.getConnection("jdbc:h2:~/test", "", "");
连接字符串的意思是数据库是存储在用户目录下的文件, 名为test.
第四步 使用JDBC API建表并插入数据
使用JDBC API, 建立user表, 包含两列.
stmt.execute("drop table user"); stmt.execute("create table user(id int primary key, name varchar(100))"); stmt.execute("insert into user values(1, 'hello')"); stmt.execute("insert into user values(2, 'world')"); ResultSet rs = stmt.executeQuery("select * from user"); while (rs.next()) { System.out.println("id " + rs.getInt("id") + " name " + rs.getString("name")); } stmt.close();