JDBC连接入门

本文介绍了使用Java实现用户登录验证的两种方法:一种是通过直接拼接SQL语句,但存在安全隐患;另一种是使用PreparedStatement对象预编译SQL语句,更为安全可靠。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.第一种方式一般不采用(有一定的漏洞)

public class LoginTest {
    @Test
    public void testLogin() {
        try {
            login("张三","123");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    /**
     * 用户登陆方法
     * @param username
     * @param password
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public void login(String username, String password) throws ClassNotFoundException, SQLException {
        //1.创建驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.创建连接
        Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/web01?useSSL=true", "root", "123456");
        //3.创建statement
        Statement stm = con.createStatement();
        //4.编写sql语句
        String sql = "select * from user where uname='"+username+"'" +" and upassword='"+password+"'";
        //5.执行sql语句
        ResultSet rs = stm.executeQuery(sql);
        if(rs.next()) {
            System.out.println("登陆成功");
        }else {
            System.out.println("用户名或密码错误");
        }
        //6.关闭连接
        if(rs!=null) rs.close();
        if(stm!=null) stm.close();
        if(con!=null) con.close();
    }
}

2.采用PreparedStatement对象(一般采用)

public class LoginTest {
    @Test
    public void testLogin() {
        try {
            login1("张三","123");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

public void login1(String username,String password) throws ClassNotFoundException, SQLException {
        //1.创建驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.创建连接
        Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/web01?useSSL=true", "root", "123456");
        //3.创建sql语句
        String sql = "select * from user where uname= ? and upassword = ?";
        //4.创建预编译对象
        PreparedStatement pstm = (PreparedStatement) con1.prepareStatement(sql);
        //5.为占位符赋值
        pstm.setString(1, username);
        pstm.setString(2, password);
        //6.执行
        ResultSet rs = pstm.executeQuery();
        if(rs.next()) {
            System.out.println("登陆成功");
        }else {
            System.out.println("登陆失败");
        }
        if(rs!=null) rs.close();
        if(pstm!=null) pstm.close();
        if(con1!=null) con1.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值