java如何连接sqlite
连接SQLite数据库的方法
在Java中连接SQLite数据库需要使用JDBC驱动。以下是详细的步骤和示例代码。
添加SQLite JDBC驱动依赖
在项目中添加SQLite JDBC驱动的依赖。如果使用Maven,可以在pom.xml中添加以下依赖:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
如果使用Gradle,可以在build.gradle中添加:
implementation 'org.xerial:sqlite-jdbc:3.36.0.3'
加载JDBC驱动并建立连接
使用Class.forName加载SQLite JDBC驱动,并通过DriverManager.getConnection建立数据库连接。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteConnection {
public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Connected to SQLite database");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
执行SQL查询
建立连接后,可以使用Statement或PreparedStatement执行SQL查询。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLiteQuery {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
statement.executeUpdate("INSERT INTO users (name) VALUES ('Alice')");
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用PreparedStatement防止SQL注入
PreparedStatement可以预编译SQL语句,提高安全性并防止SQL注入。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class SQLitePreparedStatement {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO users (name) VALUES (?)")) {
preparedStatement.setString(1, "Bob");
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
关闭资源
确保在使用完毕后关闭所有数据库资源,包括Connection、Statement和ResultSet。

try (Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users")) {
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
注意事项
- SQLite数据库文件路径可以是相对路径或绝对路径。例如,
jdbc:sqlite:/path/to/database.db。 - 如果数据库文件不存在,SQLite会自动创建。
- 在多线程环境下,确保每个线程使用独立的
Connection对象。






