Java JDBC SQLite 示例

SQLite是一个简单、小巧、快速、可靠、无服务器、零配置和无需安装的 SQL 数据库库,它与客户端应用程序在进程中运行。尽管www.sqlite.org没有官方的 JDBC 驱动程序库,但www.xerial.org提供了一个------一个 XML 数据库管理系统项目。

1.下载SQLite JDBC驱动

您可以在此处下载用于 SQLite 的最新版本的 JDBC 驱动程序。下载是按版本分类的,因此请浏览您想要的特定版本的目录:3.5.9、3.6.16、3.7.2 等。在撰写本文时,最新版本是 3.7.2,对应于 jar 文件sqlite-jdbc-3.7.2.jar。

除了 Java 类文件,jar 文件还包括适用于 Windows、Linux 和 Mac(32 位和 64 位)的 SQLite 二进制文件。

将sqlite-jdbc-VERSION.jar放入您的类路径中。

  1. SQLite JDBC 数据库连接 URL

SQLite JDBC 驱动程序可以从文件系统加载 SQLite 数据库或在内存中创建一个。

以下是文件系统数据库的数据库连接 URL 的语法:

jdbc:sqlite:database_file_path

其中database_file_path可以是相对路径或绝对路径。例如:

jdbc:sqlite:product.db

jdbc:sqlite:C:/work/product.db

这是内存数据库的数据库连接 URL 的语法:

jdbc:sqlite::memory:

jdbc:sqlite:

3.加载SQLite JDBC驱动

使用此 SQLite JDBC 库,您必须按如下方式加载驱动程序:

Class.forName("org.sqlite.JDBC");

或者:

DriverManager.registerDriver(new org.sqlite.JDBC());

  1. 建立SQLite JDBC连接

下面的示例程序创建到 SQLite 内存数据库的连接,进行一些数据库操作,并关闭连接:

java 复制代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class JavaSQLiteExample {
 
	public static void main(String args[]) {
		try {
//establish connection with database
			Class.forName("org.sqlite.JDBC");
			Connection con = DriverManager.getConnection("jdbc:sqlite::memory:");
			Statement st = con.createStatement();
//create table
			System.out.println("Create table:");
			st.executeUpdate("create table record (name text,age int)");
//insert some records
			System.out.println("Insert some records:");
			st.executeUpdate("insert into record values('neeraj',21)");
			st.executeUpdate("insert into record values('mayank',22)");
			st.executeUpdate("insert into record values('sumit',22)");
 
//reading records
			System.out.println("Reading records:");
			ResultSet rs = st.executeQuery("select * from record where age=22");
			while (rs.next()) {
				System.out.println(rs.getString("name") + " " + rs.getString("age"));
			}
			rs.close();
			st.close();
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
相关推荐
Java技术小馆4 分钟前
GitDiagram如何让你的GitHub项目可视化
java·后端·面试
Codebee21 分钟前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构
掘金-我是哪吒30 分钟前
分布式微服务系统架构第158集:JavaPlus技术文档平台日更-JVM基础知识
jvm·分布式·微服务·架构·系统架构
程序无bug36 分钟前
手写Spring框架
java·后端
程序无bug38 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
全干engineer1 小时前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
GodKeyNet1 小时前
设计模式-责任链模式
java·设计模式·责任链模式
a_Dragon11 小时前
Spring Boot多环境开发-Profiles
java·spring boot·后端·intellij-idea
abigalexy1 小时前
深入JVM底层-内存分配算法
jvm