前面说到了使用PreparedStatement接口对数据库进行增加数据操作;
现在我们来看一下修改操作和删除操作;
其实基本原理是一样的,就是sql语句有点不一样;
1.修改操作;
我们新建一个PreparedStatement_update_sql类:
package Month01.Day08.Demo03;
import java.sql.Connection;
import java.sql.PreparedStatement;
import Month01.Day08.DbUtil.DbUtil;
import Month01.Day08.Model.Book;
public class PreparedStatement_update_sql {
private static DbUtil dbUtil = new DbUtil();
private static int updateBook(Book book) throws Exception {
// 连接数据库
Connection con = dbUtil.getCon();
// sql语句
String sql = "update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=?";
// 获取PreparedStatement接口
PreparedStatement pstmt = con.prepareStatement(sql);
// 为sql中的未知量赋值
pstmt.setString(1, book.getBookName());
pstmt.setFloat(2, book.getPrice());
pstmt.setString(3, book.getAuthor());
pstmt.setInt(4, book.getBookTypeId());
pstmt.setInt(5, book.getId());
// 执行sql语句
int result = pstmt.executeUpdate();
// 关闭数据库连接
dbUtil.close(pstmt, con);
return result;
}
public static void main(String[] args) throws Exception {
Book book = new Book(6, "编程", 55, "胡大牛", 4);
int result = updateBook(book);
if (result == 1) {
System.out.println("更新数据成功!");
} else {
System.out.println("更新数据失败!");
}
}
}
将t_book表中ID为6的数据修改如上;
修改之前表中数据为:
程序执行后表中数据为:
可以看到修改成功了!
2.删除操作;
我们新建一个PreparedStatement_delete_sql类:
package Month01.Day08.Demo03;
import java.sql.Connection;
import java.sql.PreparedStatement;
import Month01.Day08.DbUtil.DbUtil;
public class PreparedStatement_delete_sql {
private static DbUtil dbUtil = new DbUtil();
private static int deleteBook(int id) throws Exception {
// 连接数据库
Connection con = dbUtil.getCon();
// 写sql语句
String sql = "delete from t_book where id=?";
// 获取PrepareStatement接口
PreparedStatement pstmt = con.prepareStatement(sql);
// 为未知量赋值
pstmt.setInt(1, id);
// 执行sql语句
int result = pstmt.executeUpdate(sql);
// 关闭数据库连接
dbUtil.close(pstmt, con);
return result;
}
public static void main(String[] args) throws Exception {
int result = deleteBook(2);
if (result == 1) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
}
将表t_book中ID为2的数据删除掉;
删除之前表中数据为:
程序执行之后表中数据为:
可以看到删除成功!