`

H2database 了解一

阅读更多

下载h2database jar包  h2-1.3.159.jar

http://www.h2database.com/html/download.html 

建一个jdbc连接项目

 buildpath加上h2-1.3.159.jar包就行了  那个data是以后生成的

JdbcConn:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

public class JdbcConn {

private Connection conn;

private PreparedStatement pstmt;

private ResultSet rs;

public static void main(String args[]) throws Exception {

JdbcConn j = new JdbcConn();

j.getConn();

j.createDatabase();

j.createData();

j.getData();

j.destory();

}

public void getConn() throws Exception {

Class.forName("org.h2.Driver");

conn = DriverManager.getConnection("jdbc:h2:data/test""sa""");

// add application code here

}

public void createDatabase() throws Exception {

pstmt = conn

.prepareStatement("create table tb(code int,name varchar(20))");

pstmt.execute();

}

public void createData() throws Exception {

Statement stmt = conn.createStatement();

stmt.addBatch("insert into tb(code,name) values(1,'luoshiqian')");

stmt.addBatch("insert into tb(code,name) values(2,'luoshiqian1')");

stmt.executeBatch();

}

public void getData() throws Exception {

pstmt = conn.prepareStatement("select * from tb");

rs = pstmt.executeQuery();

while (rs.next()) {

System.out.println("code=" + rs.getInt(1) + "     name="

rs.getString(2));

}

}

public void destory() throws Exception {

conn.close();

}

}

运行结果:

Url说明:  可以从官网Features Connecting to an Embedded (Local) Database  看到

The database URL for connecting to a local database is jdbc:h2:[file:][<path>]<databaseName>. The prefix file: is optional. If no or only a relative path is used, then the current working directory is used as a starting point. The case sensitivity of the path and database name depend on the operating system, however it is recommended to use lowercase letters only. The database name must be at least three characters long (a limitation of File.createTempFile). To point to the user home directory, use ~/, as in:jdbc:h2:~/test. 

Url连本地数据库的格试是jdbc:h2:[file:][<path>]<databaseName>

File是可选的 使用了file:的话就是使用绝对路径 如jdbc:h2:file:D:/t/test 这表示数据库文件 放去Dt文件夹下 生成的数据库文件是 test.h2.db; 数据库名+h2.db

不用file: 就是用的相对路径  例子中用的是 jdbc:h2:data/test 这表示数据库文件 放在

项目根目录下的data文件夹下  生成的数据库文件也是 test.h2.db

conn = DriverManager.getConnection("jdbc:h2:data/test""sa"""

第一次建立数据库连接的时候,数据库、用户名、密码 是自已设置的

以后创建连接就使用这些自已设置的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics