1 PreparedStatement接口
2 使用PreparedStatement接口实现增、删、改操作
代码框架与Statement类似,Book类和DbUtil类一样,只是修改了增、删、改的类
package com.chb.jdcb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.chb.model.Book;
import com.chb.util.DbUtil;
public class test {
private static DbUtil dbUtil=new DbUtil();
/**
* 添加图书
* @param book
* @return
* @throws Exception
*/
private static int addBook(Book book)throws Exception{
Connection con=dbUtil.getCon(); // 获取连接
String sql="insert into t_book values(null,?,?,?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, book.getBookName()); // 给第一个坑设置值
pstmt.setFloat(2, book.getPrice()); // 给第二个坑设置值
pstmt.setString(3, book.getAuthor()); // 给第三个坑设置值
pstmt.setInt(4, book.getBookTypeId()); // 给第四个坑设置值
int result=pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
}
public static void main(String[] args) throws Exception{
Book book=new Book("Java叉叉2", 1, "叉叉", 1);
int result=addBook(book);
if(result==1){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}
}
}
package com.chb.jdcb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.chb.model.Book;
import com.chb.util.DbUtil;
public class test1 {
private static DbUtil dbUtil=new DbUtil();
/**
* 更新图书
* @param book
* @return
* @throws Exception
*/
private static int updateBook(Book book)throws Exception{
Connection con=dbUtil.getCon();
String sql="update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=?";
PreparedStatement pstmt=con.prepareStatement(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());
int result=pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
}
public static void main(String[] args) throws Exception{
Book book=new Book(12,"K2", 2, "K", 2);
int result=updateBook(book);
if(result==1){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
}
}
package com.chb.jdcb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.chb.util.DbUtil;
public class test2 {
private static DbUtil dbUtil=new DbUtil();
/**
* 删除图书
* @param id
* @return
* @throws Exception
*/
private static int deleteBook(int id)throws Exception{
Connection con=dbUtil.getCon();
String sql="delete from t_book where id=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setInt(1, id);
int result=pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
}
public static void main(String[] args)throws Exception {
int result=deleteBook(12);
if(result==1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
}
}