import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLiteJDBCUtils {
private static final String URL = "jdbc:sqlite:path_to_your_database.db"; // 替换为你的数据库路径
static {
try {
// 加载SQLite JDBC驱动
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL);
}
// 关闭数据库连接
public static void closeQuietly(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 关闭预处理语句
public static void closeQuietly(PreparedStatement pstmt) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 关闭结果集
public static void closeQuietly(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 示例方法:执行查询操作
public static void queryDatabase(String sql, Object... params) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
}
rs = pstmt.executeQuery();
while (rs.next()) {
// 处理结果集
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeQuietly(rs);
closeQuietly(pstmt);
c
评论已关闭