ame, password);
if (user != null) {
System.out.println(user);
} else {
System.out.println("登录失败");
}
scanner.close();
}
}
public class DoLogin {
// 通过用户名密码查找用户
public User findUser(String name, String password) {
String sql = "select * from users where name = '" + name + "' and password = '" + password + "'";
// 查询数据库
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
// 只返回一条数据
System.out.println(sql);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}
}
sql 语句注入问题,添加恒成立的条件
产生的结果使输入 sql 的语句相当于 select * from users;
解决方法
public User findUser(String name, String password) {
// ? 占位符
String sql = "select * from users where name = ? and password = ?";
// 查询数据库
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
// 对 sql 语句进行预编译
preparedStatement = connection.prepareStatement(sql);
// 给 sql 语句的占位符进行赋值
// 参数1填索引, sql 语句中问号索引,
preparedStatement.setString(1, name);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
// 只返回一条数据
System.out.println(sql);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, preparedStatement, connection);
}
return user;
}