JDBC 查询数据库增删改查
时间: 2024-08-14 09:07:24 浏览: 38
JDBC (Java Database Connectivity) 是一种 Java API,用于在 Java 应用程序中访问并操作关系型数据库。通过 JDBC,开发者可以实现数据库的 CRUD (Create, Read, Update, Delete) 操作。
**创建(Create):**
```java
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, value1);
pstmt.setInt(2, value2);
pstmt.executeUpdate(); // 执行插入操作
```
**读取(Read):**
```java
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name WHERE condition");
while (rs.next()) {
String column1Value = rs.getString("column1");
int column2Value = rs.getInt("column2");
// 处理数据
}
```
**更新(Update):**
```java
String updateSql = "UPDATE table_name SET column1 = ?, column2 = ? WHERE id = ?";
pstmt.setString(1, newValue1);
pstmt.setInt(2, newValue2);
pstmt.setInt(3, id);
int rowsUpdated = pstmt.executeUpdate();
```
**删除(Delete):**
```java
String deleteSql = "DELETE FROM table_name WHERE id = ?";
pstmt.setInt(1, id);
int rowsDeleted = pstmt.executeUpdate();
```
阅读全文