写一个sqllite工具类
时间: 2024-01-21 11:01:59 浏览: 26
下面是一个简单的 SQLite 工具类的示例,提供了一些基本的增删改查操作:
```java
import java.sql.*;
public class SQLiteUtils {
private static Connection conn = null;
// 连接数据库
public static void connect(String dbPath) {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
System.out.println("SQLite 连接成功!");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
// 关闭数据库连接
public static void close() {
try {
if (conn != null) {
conn.close();
System.out.println("SQLite 连接关闭成功!");
}
} catch (SQLException e) {
System.err.println(e);
}
}
// 执行 SQL 语句
public static void executeSql(String sql) {
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
System.err.println(e);
}
}
// 查询数据
public static ResultSet query(String sql) {
ResultSet rs = null;
try {
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
System.err.println(e);
}
return rs;
}
// 插入数据
public static void insert(String tableName, String[] values) {
String sql = "INSERT INTO " + tableName + " VALUES (";
for (String value : values) {
sql += "'" + value + "',";
}
sql = sql.substring(0, sql.length() - 1) + ")";
executeSql(sql);
}
// 更新数据
public static void update(String tableName, String[] fields, String[] values, String condition) {
String sql = "UPDATE " + tableName + " SET ";
for (int i = 0; i < fields.length; i++) {
sql += fields[i] + "='" + values[i] + "',";
}
sql = sql.substring(0, sql.length() - 1) + " WHERE " + condition;
executeSql(sql);
}
// 删除数据
public static void delete(String tableName, String condition) {
String sql = "DELETE FROM " + tableName + " WHERE " + condition;
executeSql(sql);
}
}
```
使用时,可以先调用 `connect()` 方法连接到 SQLite 数据库,然后调用其他方法进行数据操作,最后调用 `close()` 方法关闭连接。
示例:
```java
public static void main(String[] args) {
SQLiteUtils.connect("test.db");
// 创建表
SQLiteUtils.executeSql("CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
// 插入数据
String[] values = {"张三", "18"};
SQLiteUtils.insert("student", values);
// 更新数据
String[] fields = {"name", "age"};
String[] newValues = {"李四", "20"};
String condition = "id=1";
SQLiteUtils.update("student", fields, newValues, condition);
// 查询数据
ResultSet rs = SQLiteUtils.query("SELECT * FROM student");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
// 删除数据
SQLiteUtils.delete("student", "id=1");
SQLiteUtils.close();
}
```