Java 中使用 SQLite 进行数据库操作379


SQLite 是一个轻量级的嵌入式数据库管理系统,以其小巧、高效和易于使用而闻名。在 Java 中使用 SQLite 可以让你轻松地管理和访问关系型数据库。

建立连接

要使用 SQLite,你首先需要创建一个连接对象。你可以使用以下代码建立连接:```java
import ;
import ;
import ;
public class SQLiteConnection {
public static void main(String[] args) {
String url = "jdbc:sqlite:/path/to/";
try {
Connection connection = (url);
("Connected to SQLite database successfully!");
();
} catch (SQLException e) {
("Error connecting to SQLite database: " + ());
}
}
}
```

执行查询

建立连接后,你可以使用 `Statement` 对象执行 SQL 查询。以下代码演示如何执行一个查询:```java
import ;
import ;
import ;
import ;
import ;
public class SQLiteQuery {
public static void main(String[] args) {
String url = "jdbc:sqlite:/path/to/";
try {
Connection connection = (url);
Statement statement = ();
String query = "SELECT * FROM table_name";
ResultSet resultSet = (query);
while (()) {
("ID: " + ("id"));
("Name: " + ("name"));
}
();
();
();
} catch (SQLException e) {
("Error executing query: " + ());
}
}
}
```

更新数据

你还可以使用 `PreparedStatement` 对象更新数据库中的数据。以下是执行更新的示例代码:```java
import ;
import ;
import ;
import ;
public class SQLiteUpdate {
public static void main(String[] args) {
String url = "jdbc:sqlite:/path/to/";
try {
Connection connection = (url);
String query = "UPDATE table_name SET name = ? WHERE id = ?";
PreparedStatement statement = (query);
(1, "New Name");
(2, 1);
int rowCount = ();
("Updated " + rowCount + " row(s) successfully!");
();
();
} catch (SQLException e) {
("Error updating data: " + ());
}
}
}
```

事务处理

事务处理允许你将多个操作组合成一个原子单元。你可以使用以下代码开始、提交或回滚事务:```java
import ;
import ;
import ;
public class SQLiteTransaction {
public static void main(String[] args) {
String url = "jdbc:sqlite:/path/to/";
try {
Connection connection = (url);
(false); // Start a transaction
// Execute multiple operations
(); // Commit the transaction
();
} catch (SQLException e) {
(); // Rollback the transaction
("Error in transaction: " + ());
}
}
}
```

使用 Java 中的 SQLite 可以让你轻松管理和访问关系型数据库。通过建立连接、执行查询、更新数据和处理事务,你可以使用 SQLite 存储和检索信息,以及执行各种数据库操作。

2024-12-02


上一篇:Java 类方法:揭秘 static 的魔力

下一篇:Java 数组与 List:全方位比较