javaee中用preparestatment实现mysql 增删改查preparestatment
时间: 2023-07-07 09:32:23 浏览: 169
在JavaEE中,可以使用PreparedStatement对象来执行MySQL数据库的增删改查操作。PreparedStatement对象是对Statement对象的扩展,可以通过占位符(?)来设置参数,提高SQL语句的执行效率和安全性。
以下是基于PreparedStatement对象实现MySQL的增删改查操作的示例代码:
1. 增加数据:
```
String sql = "INSERT INTO user(name, age, sex) VALUES(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Tom");
pstmt.setInt(2, 20);
pstmt.setString(3, "M");
int result = pstmt.executeUpdate();
```
2. 删除数据:
```
String sql = "DELETE FROM user WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
int result = pstmt.executeUpdate();
```
3. 修改数据:
```
String sql = "UPDATE user SET age=? WHERE name=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 22);
pstmt.setString(2, "Tom");
int result = pstmt.executeUpdate();
```
4. 查询数据:
```
String sql = "SELECT * FROM user WHERE name=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Tom");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
}
```
阅读全文