设为首页 加入收藏

TOP

数据库之JDBC操作及实例讲解(四)
2018-03-24 09:50:28 】 浏览:358
Tags:数据库 JDBC 操作 实例 讲解
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;
}
首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇java之数据库连接JDBC教程 下一篇MySQL数据库管理、表管理及增删改..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目