文章目录
1.导入依赖
bash
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
</dependencies>
2.实际应用
bash
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLiteExample {
// 数据库文件路径
private static final String DB_PATH = "your_database.db";
public static void main(String[] args) {
createTable();
insertData("John Doe", 25);
queryData();
}
// 创建表
public static void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS users (name TEXT, age INT)";
executeSQL(sql);
}
// 插入数据
public static void insertData(String name, int age) {
String sql = "INSERT INTO users (name, age) VALUES (?,?)";
executeUpdate(sql, name, age);
}
// 查询数据
public static void queryData() {
String sql = "SELECT * FROM users";
executeQuery(sql);
}
// 执行 SQL 语句(创建表等)
public static void executeSQL(String sql) {
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 执行更新操作(插入数据等)
public static void executeUpdate(String sql, Object... params) {
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 执行查询操作
public static void executeQuery(String sql) {
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
}
}
在上述示例中:
- 定义了数据库文件的路径。
- 提供了创建表、插入数据和查询数据的方法。
- 通过 getConnection 方法获取与 SQLite 数据库的连接。
将 your_database.db 替换为实际的数据库文件路径,并根据需要修改表结构和数据操作的逻辑。