一、登录异常
1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
使用 try / catch 的方式处理 forname 异常
2.创建连接
connection = DriverManager.getConnection();
3.写SQL语句
String sql = "select * from user where username=? and password=?";
用?代替一个字节,进行占位
System.out.println("请输入用户名:");
String name = input.next();
System.out.println("请输入密码:");
String password = input.next();
4.得到statement对象
5.执行SQL语句得到结果集
statement = connection.prepareStatement(sql);
statement.setString(1,name);
statement.setString(2,password);
并对"name" "password"进行赋值
6.处理结果集
if(resultSet.next()){
System.out.println("登陆成功!");
}else{
throw new LoginException("用户名或密码错误");
}
} catch (SQLException e) {
e.printStackTrace();
7.关闭资源
finally {
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
8.异常类
public class LoginException extends Exception{
public LoginException(String message) {
super(message);
}
}