Java连接数据库的增删改查
时间: 2024-12-04 14:11:54 浏览: 6
在Java中,连接数据库通常涉及使用JDBC (Java Database Connectivity) API。以下是基本的增删改查操作:
1. **插入(Insertion)**:
使用Statement或PreparedStatement构造SQL INSERT语句,如:
```java
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, value1);
pstmt.setInt(2, value2);
pstmt.executeUpdate();
```
2. **删除(Deletion)**:
同样构造DELETE语句并设置条件,例如:
```java
String sql = "DELETE FROM table_name WHERE condition";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, conditionValue);
pstmt.executeUpdate();
```
3. **更新(Updating)**:
类似地,使用UPDATE语句,并指定要修改的字段和新值:
```java
String sql = "UPDATE table_name SET column1 = ? WHERE condition";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, newValue);
pstmt.setString(2, conditionValue);
pstmt.executeUpdate();
```
4. **查询(Retrieval)**:
SELECT语句用于获取数据,可以使用ResultSet来遍历结果:
```java
String sql = "SELECT * FROM table_name WHERE condition";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String column1 = rs.getString("column1");
// 处理其他列...
}
```
阅读全文