1.第一种方式一般不采用(有一定的漏洞)
public class LoginTest {
@Test
public void testLogin() {
try {
login("张三","123");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 用户登陆方法
* @param username
* @param password
* @throws ClassNotFoundException
* @throws SQLException
*/
public void login(String username, String password) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/web01?useSSL=true", "root", "123456");
Statement stm = con.createStatement();
String sql = "select * from user where uname='"+username+"'" +" and upassword='"+password+"'";
ResultSet rs = stm.executeQuery(sql);
if(rs.next()) {
System.out.println("登陆成功");
}else {
System.out.println("用户名或密码错误");
}
if(rs!=null) rs.close();
if(stm!=null) stm.close();
if(con!=null) con.close();
}
}
2.采用PreparedStatement对象(一般采用)
public class LoginTest {
@Test
public void testLogin() {
try {
login1("张三","123");
} catch (Exception e) {
e.printStackTrace();
}
}
public void login1(String username,String password) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/web01?useSSL=true", "root", "123456");
String sql = "select * from user where uname= ? and upassword = ?";
PreparedStatement pstm = (PreparedStatement) con1.prepareStatement(sql);
pstm.setString(1, username);
pstm.setString(2, password);
ResultSet rs = pstm.executeQuery();
if(rs.next()) {
System.out.println("登陆成功");
}else {
System.out.println("登陆失败");
}
if(rs!=null) rs.close();
if(pstm!=null) pstm.close();
if(con1!=null) con1.close();
}
}