Java JDBC SQLite 示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLiteExample {
private Connection connection = null;
private final String DB_URL = "jdbc:sqlite:path_to_your_database.db";
public SQLiteExample() {
try {
// 加载SQLite JDBC驱动
Class.forName("org.sqlite.JDBC");
// 建立连接
this.connection = DriverManager.getConnection(DB_URL);
// 执行查询
this.executeQuery();
} catch (ClassNotFoundException e) {
System.out.println("SQLite JDBC 驱动未找到");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库连接失败");
e.printStackTrace();
} finally {
this.closeConnection();
}
}
private void executeQuery() {
try {
// 创建预处理语句
PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM your_table_name"
);
// 执行查询
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// 处理结果集
System.out.println(resultSet.getString("column_name"));
}
// 关闭结果集
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void closeConnection() {
try {
if (this.connection != null) {
// 关闭连接
this.connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SQLiteExample();
}
}
这个示例代码展示了如何使用Java JDBC连接SQLite数据库,执行一个简单的查询,并处理结果集。注意,你需要将path_to_your_database.db
替换为实际的数据库路径,your_table_name
替换为你的表名,column_name
替换为你想要获取的列名。
评论已关闭