海阔天空

当前时间为:
欢迎大家来到海阔天空https://www.9713job.com,广告合作以及淘宝商家推广请微信联系15357240395

2020Javaweb教程之JDBC实现用户登录

未分类
2020-10-14 13:20:03
1822677238@qq.com

手机扫码查看

2020Javaweb教程之JDBC实现用户登录

2020Javaweb教程之JDBC实现用户登录

import java.sql.*;
import java.util.Scanner;

public class JDBCforLogin {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=sc.nextLine();
        System.out.println("请输入密码:");
        String password=sc.nextLine();
        login(username,password);
    }



    public static void login(String username,String password){
        Connection connection=null;
        PreparedStatement PreparedStatement=null;
        ResultSet resultSet=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demos", "root", "root");
            // ? 为占位符
            String sql="select username,password from users where username=? and password=?";
            // 预编译sql语句
            PreparedStatement=connection.prepareStatement(sql);
            //为每个占位符赋予一个值
            PreparedStatement.setString(1,username);
            PreparedStatement.setString(2,password);
            resultSet = PreparedStatement.executeQuery();
            if (resultSet.next()) {
                System.out.println("登录成功");
            }else System.out.println("登录失败");
        }catch (Exception e){}finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (PreparedStatement != null) {
                    PreparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {}
        }
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注