java链接sqlite

本文介绍如何使用 SQLite 的 JDBC 驱动来连接并操作 SQLite 数据库。包括下载 JDBC 驱动、配置 classpath 和示例代码等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天折腾了好久sqlite,刚刚搞定。以下是参照内容。

链接步骤:

Usage:
  1. Download sqlite-jdbc-(VERSION).jar from http://www.xerial.org/maven/repository/artifact/org/xerial/sqlite-jdbc/, then append this jar file into your classpath.
  2. load the JDBC driver org.sqlite.JDBC from your code. (see the example below)
  • Usage Example (Assuming sqlite-jdbc-(VERSION).jar is placed in the current directory)
> javac Sample.java
> java -classpath ".;sqlite-jdbc-(VERSION).jar"Sample   # in Windows
or
> java -classpath ".:sqlite-jdbc-(VERSION).jar"Sample   # in Mac or Linux
name
= leo
id
=1
name
= yui
id
=2
  • Sample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


publicclassSample
{
 
publicstaticvoid main(String[] args)throwsClassNotFoundException
 
{
   
// load the sqlite-JDBC driver using the current class loader
   
Class.forName("org.sqlite.JDBC");
   
   
Connection connection =null;
   
try
   
{
     
// create a database connection
      connection
=DriverManager.getConnection("jdbc:sqlite:sample.db");
     
Statement statement = connection.createStatement();
      statement
.setQueryTimeout(30);  // set timeout to 30 sec.
     
      statement
.executeUpdate("drop table if exists person");
      statement
.executeUpdate("create table person (id integer, name string)");
      statement
.executeUpdate("insert into person values(1, 'leo')");
      statement
.executeUpdate("insert into person values(2, 'yui')");
     
ResultSet rs = statement.executeQuery("select * from person");
     
while(rs.next())
     
{
       
// read the result set
       
System.out.println("name = "+ rs.getString("name"));
       
System.out.println("id = "+ rs.getInt("id"));
     
}
   
}
   
catch(SQLException e)
   
{
     
// if the error message is "out of memory",
     
// it probably means no database file is found
     
System.err.println(e.getMessage());
   
}
   
finally
   
{
     
try
     
{
       
if(connection !=null)
          connection
.close();
     
}
     
catch(SQLException e)
     
{
       
// connection close failed.
       
System.err.println(e);
     
}
   
}
 
}
}

The usage of SQLite-JDBC driver is the same with the original version. See http://www.zentus.com/sqlitejdbc/ for the general usage. For usage of JDBC, see my article about JDBC.

 

关键是要指定jdbc文件在classpath里,否则会找不到。

 

原文:http://code.google.com/p/sqlite-jdbc/wiki/Introduction#Usage

转载于:https://www.cnblogs.com/simpman/archive/2013/04/24/3041151.html

### 如何使用Java连接SQLite数据库Java中连接SQLite数据库通常需要借助第三方驱动程序 `org.xerial.sqlite-jdbc`。以下是详细的说明以及示例代码。 #### 依赖项引入 为了能够通过Java访问SQLite数据库,首先需要导入SQLite JDBC驱动。如果项目基于Maven构建,则可以在项目的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.41.2.1</version> <!-- 版本号可能随时间更新 --> </dependency> ``` 对于非Maven项目,可以从[Maven Central Repository](https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc)下载JAR包并手动将其加入classpath。 --- #### 示例代码:建立与SQLite的连接 下面展示了一个完整的Java代码片段,演示如何加载SQLite驱动、创建数据库连接,并执行基本的SQL语句。 ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class SQLiteConnectionExample { public static void main(String[] args) { Connection conn = null; try { // 加载SQLite JDBC驱动 Class.forName("org.sqlite.JDBC"); // 定义数据库路径(相对路径或绝对路径) String url = "jdbc:sqlite:sample.db"; // 建立数据库连接 conn = DriverManager.getConnection(url); System.out.println("成功连接到SQLite数据库"); // 创建一个Statement对象以发送SQL语句给数据库 Statement stmt = conn.createStatement(); // 执行一条SQL命令来创建新表 String sqlCreateTable = "CREATE TABLE IF NOT EXISTS users (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL," + "age INT)"; stmt.execute(sqlCreateTable); // 插入一些测试数据 String sqlInsert = "INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25)"; stmt.executeUpdate(sqlInsert); System.out.println("表格已创建并插入初始数据"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } finally { try { if (conn != null && !conn.isClosed()) { conn.close(); // 关闭数据库连接 } } catch (Exception ex) { System.err.println(ex.getClass().getName() + ": " + ex.getMessage()); } } } } ``` 此代码实现了以下几个功能: 1. **加载SQLite驱动**:通过调用`Class.forName()`显式注册SQLite JDBC驱动[^3]。 2. **指定数据库URL**:使用标准格式`jdbc:sqlite:<path>`指明目标数据库的位置。 3. **创建和关闭连接**:利用`DriverManager.getConnection()`方法获得数据库连接;并通过`finally`块确保资源释放。 4. **执行SQL指令**:展示了如何创建表结构以及向其中插入记录。 --- #### 可能遇到的问题及其解决办法 ##### 问题1:找不到驱动类 (`ClassNotFoundException`) 原因可能是未正确添加SQLite JDBC库至项目环境。确认是否按照前述指导完成了相应设置。 ##### 问题2:无法定位数据库文件 当提供错误路径或者试图操作不存在的文件时会发生此类异常。建议先验证路径准确性再尝试重新部署逻辑。 ##### 问题3:权限不足导致失败 某些情况下因操作系统安全策略限制可能导致I/O受限情况发生,请赋予适当读写许可权以便顺利存取资料档案。 以上均需依据具体报错信息逐一排查修正。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值