private static final String URL_ = "jdbc:mysql://127.0.0.1:3306/test01";
private static final String USER = "root";
private static final String PASSWORD = "123456";
@Test
public void testLogin() {
try {
// login1("qweasd' or 'zs", "123");
login1("qweasd", "123");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
System.err.println("类无法加载异常");
System.err.println("SQL异常");
}
}
public void login1(String uname, String upassword)
throws ClassNotFoundException, SQLException {
//
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 注册驱动
connection = DriverManager.getConnection(URL_, USER, PASSWORD);
// sql语句
String sql = "SELECT * FROM USERS WHERE UNAME=? AND UPASSWORD=?";
// 预编译
preparedStatement = connection.prepareStatement(sql);
// 查询类型
preparedStatement.setString(1, uname);
preparedStatement.setString(2, upassword);
// 查询
resultSet = preparedStatement.executeQuery();
// 结果
if (resultSet.next()) {
System.out.println(sql);
System.out.println("登陆成功 " + uname);
System.out.println(resultSet.getString("UID") + " "
+ resultSet.getString("UNAME") + " "
+ resultSet.getString("UPASSWORD"));
} else {
System.out.println("账号或密码错误");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (resultSet != null)
resultSet.close();
if (preparedStatement != null)
preparedStatement.close();
if (connection != null)
connection.close();
}
}