帮我用jdbc写个增删改查
时间: 2023-05-20 20:02:30 浏览: 77
好的,以下是使用 JDBC 进行增删改查的示例代码:
1. 建立数据库连接
```
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
```
2. 插入数据
```
String sql = "INSERT INTO user (name, age) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 20);
pstmt.executeUpdate();
```
3. 查询数据
```
String sql = "SELECT * FROM user WHERE age > ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 18);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getInt("age"));
}
```
4. 更新数据
```
String sql = "UPDATE user SET age = ? WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 21);
pstmt.setString(2, "张三");
pstmt.executeUpdate();
```
5. 删除数据
```
String sql = "DELETE FROM user WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.executeUpdate();
```
注意:以上代码仅供参考,实际应用中需要根据具体情况进行修改。
阅读全文