import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLiteJDBCExample {
private Connection connection = null;
private final String DB_URL = "jdbc:sqlite:sample.db"; // SQLite数据库文件路径
// 连接SQLite数据库(如果不存在则创建)
public void connectToDB() {
try {
connection = DriverManager.getConnection(DB_URL);
System.out.println("连接SQLite数据库成功!");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// 创建表
public void createTable() {
try {
String sql = "CREATE TABLE IF NOT EXISTS user_tb " +
"(id INTEGER PRIMARY KEY, name TEXT, email TEXT)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
System.out.println("创建表成功!");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// 插入数据
public void insertData(String name, String email) {
try {
String sql = "INSERT INTO user_tb(name, email) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, email);
statement.executeUpdate();
System.out.println("数据插入成功!");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// 查询数据
public void readData() {
try {
String sql = "SELECT id, name, email FROM user_tb";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// 关闭数据库连接
public void closeConnection() {
try {
if (connection != null) {
connection.close();
S
评论已关闭