sqlite的java使用

星期三, 2011-06-08 | Author: Lee | JAVA-and-J2EE, linux | 5,012 views

sqlite大名鼎鼎的文本存储,支持sql的方式和带事务支持,sqlite是c写的,官方没有java的api使用,在开源中找到2中方式:

SQLiteJDBC:http://www.zentus.com/sqlitejdbc/,这是一个纯Java的实现,无需安装sqlite,官方号称用c转成java的实现方式,用起来相当方便,引入此jar即可,方便使用,可能效率会慢点;
SQLite Java Wrapper: http://www.ch-werner.de/javasqlite,安装的时候需要本地库,比如windows下的dll文件,和SQLiteJDBC的优缺点相反,还要自行去编译,比较麻烦;
下面是 使用SQLiteJDBC的应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.i5a6.sqlite.test;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class Test {
	public static void main(String[] args) throws Exception {
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection("jdbc:sqlite:i5a6.db");
		Statement stat = conn.createStatement();
		stat.executeUpdate("drop table if exists people;");
		stat.executeUpdate("create table people (name, occupation);");
		PreparedStatement prep = conn
				.prepareStatement("insert into people values (?, ?);");
		prep.setString(1, "Gandhi");
		prep.setString(2, "politics");
		prep.addBatch();
		prep.setString(1, "Turing");
		prep.setString(2, "computers");
		prep.addBatch();
		prep.setString(1, "中文国际");
		prep.setString(2, "i5a6");
		prep.addBatch();
 
		conn.setAutoCommit(false);
		prep.executeBatch();
		conn.setAutoCommit(true);
 
		ResultSet rs = stat.executeQuery("select * from people;");
		while (rs.next()) {
			System.out.println("name = " + rs.getString("name"));
			System.out.println("job = " + rs.getString("occupation"));
		}
		rs.close();
		conn.close();
	}
}

Tags: , , , ,

文章作者: Lee

本文地址: https://www.pomelolee.com/783.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta