- 工具类的封装(重点)
public class LoginTest {
public static void main(String[] args) {
System.out.println("请输入用户名");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
if(login2(username,password)){
System.out.println("登录成功~!");
}else{
System.out.println("登录失败~!");
}
}
private static boolean login2(String username, String password) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("select count(*) from user where username=? and password=?");
prst.setString(1,username);
prst.setString(2,password);
rs = prst.executeQuery();
if(rs.next()){
int result = rs.getInt(1);
return result>0;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,prst,conn);
}
return false;
}
private static boolean login(String username, String password) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
st = conn.createStatement();
String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'";
rs = st.executeQuery(sql);
if(rs.next()){
int result = rs.getInt(1);
return result>0;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,st,conn);
}
return false;
}
}
public class DBUtils {
private static Properties p = new Properties();
static{
try {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
p.load(is);
Class.forName(p.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password")