ユーザーログインケースのJDBC+mysql実装

要件:ユーザー名とパスワードを入力して、データベースにあるかどうかを確認します

mysqlはログインデータベースを作成し、テーブルユーザーを作成します

2つのデータを挿入します

   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