HSQLDB In-Process方式访问内存数据库

 

 

HSQLDB一大特色就是能够在内存中建立数据库,当然它也能将这些内存数据库保存到文件中以便实现真正的持久化。

 

先睹为快!

 

下面是一个In-Process方式访问内存数据库的代码示例:

 

 

下面代码需要引入hsqldb.jar包 (hsqldb-2.2.8)

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {

	public static void main(String[] args) {
		try {
			//加载HSQLDB的JDBC驱动
			Class.forName("org.hsqldb.jdbcDriver");
			//在内存中建立数据库memdb,用户名为sa,密码为空
			Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:memdb","username","password");
			System.out.println("connect to memdb OK");
			
			Statement stat = conn.createStatement();
			//新建数据表
			stat.executeUpdate("create table person(NAME VARCHAR(20), AGE INTEGER)");
			System.out.println("create TABLE:person OK");
			
			//插入数据
			stat.executeUpdate("INSERT INTO person VALUES('张三丰',22)");
			stat.executeUpdate("INSERT INTO person VALUES('amos','25')");
			System.out.println("insert data into TABLE:person OK!");

			conn.close();
			
//			stat.execute("SHUTDOWN");
//			System.out.println("SHUTDOWN");
			
			Connection conn2 = DriverManager.getConnection("jdbc:hsqldb:mem:memdb","username","password");
			
			//查询数据
			PreparedStatement pstmt = conn2.prepareStatement("SELECT * FROM person");
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()) {
				String s = null;
				s = rs.getString(1) + "," + rs.getString(2);
				System.out.println(s);
			}
			System.out.println("select data OK");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 直接在内存中

 

你可能感兴趣的:(HSQLDB In-Process方式访问内存数据库)