jdbc使用 PreparedStatement 接口实现更新数据操作

jdbc使用 PreparedStatement  接口实现更新数据操作

package chap04.sec03;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


import model.Book;
import util.DbUtil;


public class Demo1 {


private static DbUtil dbUtil=new DbUtil();
private static int updateBook(Book book) throws SQLException{

String sql="update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=? "; 
Connection con= dbUtil.getCon();
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.closeCon(pstmt, con);
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Book book=new Book(4,"javaqwe4",444,"李四4",4);
try {
int result =updateBook(book);
if(result==1){
System.out.println("更新成功");
}
else{
System.out.println("更新失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

你可能感兴趣的:(JDBC)