首頁 > 軟體

java如何連線資料庫executeUpdate()和executeQuery()

2022-03-23 16:00:33

executeUpdate

Update

//沒有返回值
public void update(int count){
conn=DBUtil.getConn();
String sql="update counter set count=?";
try {					
			PreparedStatement ps = conn.prepareStatement(sql);
			//傳進去的
			ps.setInt(1,count);
			ps.executeUpdate();		
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.closeConn();
		}   
}

Insert

//沒有返回值,引數是個字串部門名稱就ok了,因為id的話是自增
	public void insert(String departmentname) {
		conn = ConnectionFactory.getConnection();
		String sql = "insert into department (departmentname) values(?)";
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, departmentname);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection();
		}
	}
 //因為employeeid自增,所以不用設定
public void insert(Employee employee){
		  conn=ConnectionFactory.getConnection();
		  String sql="insert into employee"
				  +
					"(employeename,username,password,phone,email,departmentid,status,role)" +
					" values(?,?,?,?,?,?,?,?)";
		  try {		
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,employee.getEmployeename());
			pstmt.setString(2,employee.getUsername());
			pstmt.setString(3,employee.getPassword() );
			pstmt.setString(4,employee.getPhone() );
			pstmt.setString(5,employee.getEmail());
			pstmt.setInt(6,employee.getDepartmentid());			
			//註冊成功後,預設為正在稽核,status為0
			pstmt.setString(7,"0");
			//註冊時,預設為員工角色,role值為2
			pstmt.setString(8,"2");
			pstmt.executeUpdate();	
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			ConnectionFactory.closeConnection();
		}	  
	  }

Delete

//刪除不用返回值	
public void delete(int departmentid) {
		conn = ConnectionFactory.getConnection();
		String sql = "delete from department where departmentid=?;";
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, departmentid);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection();
		}
	}

select

//返回int型別
public int select(){
	int count=0;
	conn=DBUtil.getConn();
	String sql = "select * from counter";
	try{
		PreparedStatement ps = conn.PreparedStatement(sql);
		ResultSet rs =ps.excuteQuery();
		if(rs.next()){
			count=rs.getInt("visitcount");
		}
	}catch{
 
	}finally{
		DBUtil.closeConn();
	}
	return count;
}
//返回部門集合
	public List<Department> selectAll() {
		conn = ConnectionFactory.getConnection();
		// 新建一個集合departmentsList
		List<Department> departmentsList = new ArrayList<Department>();
		try {
			Statement st = null;
			String sql = "select * from department";
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			Department department;
			while (rs.next()) {
				// 新建一個department來接收資料庫的資訊
				department = new Department();
				department.setDepartmentid(rs.getInt("departmentid"));
				department.setDepartmentname(rs.getString("departmentname"));
				departmentsList.add(department);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection();
		}
		// 返回集合
		return departmentsList;
	} 
 
//返回員工
  public List<Employee> selectAllEmployee(){
			 conn=ConnectionFactory.getConnection();
			 List<Employee> employeeslist=new ArrayList<Employee>();
			 Employee employee=null;	
			 try {
				PreparedStatement st=null;
				//只查詢已註冊且未審批 且 角色是員工的
				String sql="select * from employee where role='2' and status='0'";
		 		st = conn.prepareStatement(sql);
				ResultSet rs =st.executeQuery(sql);
				while(rs.next()){
					employee=new Employee();
					employee.setEmployeeid(rs.getInt("employeeid"));
					employee.setEmployeename(rs.getString("employeename"));
					employee.setUsername(rs.getString("username"));
					employee.setPhone(rs.getString("phone"));
					employee.setEmail(rs.getString("email"));
					employee.setStatus(rs.getString("status"));
					employee.setDepartmentid(rs.getInt("departmentid"));
					employee.setPassword(rs.getString("password"));
					employee.setRole(rs.getString("role"));
					employeeslist.add(employee);
				}
			 } catch (SQLException e) {
				    e.printStackTrace();
			}finally{
				//最後總要關閉連線
				ConnectionFactory.closeConnection();
			}
			 return employeeslist;
		 } 
 
public Employee selectByNamePwd(String username, String pwd) {
		Employee employee = null;
		try {
			//建立PreparedStatement物件
			PreparedStatement st = null;
			//查詢語句
			String sql = "select * from employee where username='" + username + "' and  password='" + pwd + "'";
			st = conn.prepareStatement(sql);
			ResultSet rs = st.executeQuery(sql);
			//判斷結果集有無記錄,如果有:則把內容取出來,變成一個employee物件,並且返回它
			if (rs.next() == true) {				
				employee = new Employee();				
				employee.setEmployeeid(rs.getInt("employeeid"));
				employee.setEmployeename(rs.getString("employeename"));
				employee.setUsername(rs.getString("username"));
				employee.setPhone(rs.getString("phone"));
				employee.setEmail(rs.getString("email"));
				employee.setStatus(rs.getString("status"));
				employee.setDepartmentid(rs.getInt("status"));
				employee.setPassword(rs.getString("password"));
				employee.setRole(rs.getString("role"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionFactory.closeConnection();
		}
		return employee;
	}
 public Employee selectByUsername(String username){
		 conn=ConnectionFactory.getConnection();
		 Employee employee=null;	
		 try {
			 PreparedStatement st=null;
			String sql="select * from employee where username='"+username+"'";
	 		st = conn.prepareStatement(sql);
			ResultSet rs =st.executeQuery(sql);
			if(rs.next()==true){
				employee=new Employee();
				employee.setEmployeeid(rs.getInt("employeeid"));
				employee.setEmployeename(rs.getString("employeename"));
				employee.setUsername(rs.getString("username"));
				employee.setPhone(rs.getString("phone"));
				employee.setEmail(rs.getString("email"));
				employee.setStatus(rs.getString("status"));
				employee.setDepartmentid(rs.getInt("status"));
				employee.setPassword(rs.getString("password"));
				employee.setRole(rs.getString("role"));
			}
		 } catch (SQLException e) {
			    e.printStackTrace();
		}finally{
			ConnectionFactory.closeConnection();
		}
		 return employee;
	 }

需要注意的點

1.字串的拼接必須在雙引號的基礎上被單引號套住

上面有個小陷阱

如果加了

會正常執行,如果沒有加,會因為欄位不是字串而報錯.

結果集為空

2.在Bean類,預設的構造方法還與引數順序有關

也就是說public Employee(String user,int id, String pwd){}

和 public Employee(int id,String user,String pwd){}  是不一樣的構造方法

測試main方法裡,插入的資料的型別順序決定了呼叫哪個構造方法.

3.構造方法的方法名就是類名....

4.system.out.println 裡列印加不加toString的區別

看起來沒有區別(這個不敢肯定)

5.sql語句裡,雙引號的裡面套雙引號,會有歧義

會報錯

應該在裡面放單引號

execute()和executeUpdate()主要區別

  • execute()返回一個boolean型別值,true表示第一個結果是ResultSet物件,false表示第一個結果是沒有結果的更新語句(insert,delete,update)。
  • executeUpdate()返回一個int型別值,表示有幾條資料受到了影響。

此外,execute()還可以通過getResultSet()獲得執行語句後的結果;

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com