PreparedStatement的更新操作。
package revjdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import model.student;
import Util.Dbutil;
public class PreparedUpdateDemo {
public static Dbutil db=new Dbutil();
public static int update(student student)throws Exception
{
Connection con=db.getCon();
String sql="update student set name=?,age=? ,sex=?where sno=?";
PreparedStatement pst=con.prepareStatement(sql);//在SQL?之后就要设置值,preparedstatement先预编译,之后设置值,真正的执行
pst.setString(1, student.getName());
pst.setInt(2, student.getAge());
pst.setString(3, student.getSex());
pst.setString(4, student.getSno());
int rs=pst.executeUpdate();//更新操作
System.out.println("改动了"+rs+"行");
return rs;
}
public static void main(String[] args)throws Exception {
student student=new student("9800","nini",80,"0");
update(student);
}
}
package chap04;
import java.sql.Connection;
import java.sql.PreparedStatement;
import util.Dbutil;
/**
* 删除图书
* @author cyj
*
*/
public class demo3 {
private static Dbutil dbutil = new Dbutil();
private static int deletebook(int id) throws Exception {
Connection con = dbutil.getCon();
String sql = "delete from mybook where id=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,id);
int result = pstmt.executeUpdate();// 返回sql执行结果
dbutil.close(pstmt, con);
return result;// ctrl+a 全选 ctrl+sh
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int res=deletebook(6);
if(res==1)
{
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}
}