1. 程式人生 > >PreparedStatement的更新,刪除操作

PreparedStatement的更新,刪除操作

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("刪除失敗");
						}
	}
	}