如何在Java中使用SQLite数据库

用一个小例子熟悉下如何在Java中使用SQLite数据库,要在Java中使用SQLite数据库首先需要导入jar包,下载地址在这里

代码如下:

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

public class TestSQLite {
	public static void main(String[] args) {
		try {
			Class.forName("org.sqlite.JDBC");
			//参数中的c:/test3.db代表在c盘的目录下创建数据库文件test3.db
			Connection conn = DriverManager.getConnection("jdbc:sqlite:c:/test3.db"); 
			
			//创建表
			String sql = "create table person(id INTEGER primary key autoincrement, name TEXT)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.execute();
			System.out.println("*********create table person OK*********");
			
			//插入数据
			String insertSql = "insert into person(name) values(?)";
			ps = conn.prepareStatement(insertSql);
			//注意第一个参数从1开始而不是0
			ps.setString(1, "zhangsan");
			ps.execute();
			System.out.println("*********insert into person OK*********");
			
			//查找
			String querySql = "select * from person";
			ps = conn.prepareStatement(querySql);
			ResultSet rs = ps.executeQuery();
			//用rs.next()方法来遍历数据库的游标
			while(rs.next()){
				//得到游标中的字段值,索引也是从1开始的
				String id = rs.getString(1);
				String name = rs.getString(2);
				System.out.println("id = " + id);
				System.out.println("name = " + name);
			}
			System.out.println("*********query from person OK*********");
			
			//删除
			String deleteSql = "delete from person where id=?";
			ps = conn.prepareStatement(deleteSql);
			ps.setInt(1, 1);
			ps.execute();
			System.out.println("*********delete from person OK*********");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}


你可能感兴趣的:(Java,Java,SQLite,数据库)