JDBC+mysql implementation of user login case

Requirements: Enter username and password to determine whether it is in the database

mysql creates the login database and creates the table user

Insert two data

   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注入问题

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123969112