package example;
import java.sql.*;
import java.util.*;
public class CheckUser{
//获得提交的用户名和密码
private String user="";
private String password="";
public void setUser(String user){
this.user=user;
}
public void setPassword(String password){
this.password=password;
}
//连接数据库对象初始化
Connection con=null;
PreparedStatement stmt=null;
ResultSet result=null;
String url="jdbc:mysql://localhost:8080/test";
String name="root";
String pass="123456";
//连接数据库
public CheckUser(){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url,name,pass);
}catch(Exception e){
System.out.println(e);
}
}
//验证身份
public boolean CheckRole(){
boolean ifright=false;
try{
String sql="Select *from users where ID=? and PASSWORD=?";
stmt=con.prepareStatement(sql);
stmt.setString(1,user);
stmt.setString(2,password);
result=stmt.executeQuery(sql);
if(result.next())
ifright=true;
else
ifright=false;
result.close();
stmt.close();
con.close();
}catch(Exception e1){
System.out.println(e1);
}
return ifright;
}
}
关闭Connection;PreparedStatement;ResultSet在finally里面关闭,确保在出现异常的时候也关闭资源。关闭的时候要先判断是否为空,不然会出空指针异常。