JDBC+mysql实现用户登录案例

需求:输入username和password,判断是否在数据库中

mysql创建login数据库,并创建表user

先插入两条数据

   public static boolean login(String username,String password) throws SQLException {
        if(username!=null&&password!=null){
            //连接数据库
            Connection connection=JDBCUtils.getConnection();
            String sql="select * from user where username= ? and password = ?";
            PreparedStatement preparedStatement =connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            ResultSet resultSet=preparedStatement.executeQuery();
            if(resultSet.next())return true;
            return false;
        }
        return false;
    }
    public static void main(String[] args) throws SQLException {
        Scanner sc=new Scanner(in);
        String user=sc.next();
        String password=sc.next();
        System.out.println(login(user,password));
    }
1、使用JDBCUtils工具类化简代码
2、使用PreparedStatemet对象,执行动态sql语句,防止sql注入问题

猜你喜欢

转载自blog.csdn.net/m0_52043808/article/details/123969112