JDBC的使用(二):PreparedStatement接口;ResultSet接口(获取结果集);例题:SQL注入...

ResultSet接口:类似于一个临时表,用来暂时存放数据库查询操作所获得的结果集。

getInt(), getFloat(), getDate(), getBoolean(), getString(), getObject(), next(),:将指针向下移一行。

例一:(输入用户名和密码验证是否登录成功):用Statement接口会导致,SQL注入!

下图是代码:

package com.inba.maya.chaxun;

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

public class Text {
    
    public static void main(String[] args) throws Exception{
        Scanner sc=new Scanner(System.in);
        System.out.print("请输入用户名:");
        String yhm=sc.nextLine();
        System.out.print("请输入密码:");
        String mm=sc.nextLine();
        //第一种解决的方法:给用户名进行替换,把'换成".
        //yhm=yhm.replaceAll("\'", "\"");
        //一加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //二链接数据库
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK","root","");
        //创建SQL语句
        Statement stat=conn.createStatement();
        //采用字符串拼接的房方法会导致,SQL注入,从而导致错误发生,如控制台所示
        //原因是:当我输入: sl服务网16' or 1=1 #;在代码中显示的是:
    
//所以当我输入的里面有'时就会和前面的'相匹配,or 1=1永远成立 #在SQL语句中是注释,所以才会登陆成功
        String s="select * from user where username='"+yhm+"' and pasword='"+mm+"'";
        ResultSet rs=stat.executeQuery(s);
        if(rs.next()==true){
            System.out.println("登陆成功,欢迎"+rs.getString(3));
        }else{
            System.out.println("对不起,您输入的用户名或密码不正确!");PreparedStatement
        }
        conn.close();
    }

}

解决的方法1:

第一种解决的方法:给用户名进行替换,把'换成".
yhm=yhm.replaceAll("\'", "\"");

 解决的第二种方法:

用PreparedStatement接口,该接口继承自Statement接口,但是用于执行动态的SQL语句。通过PreparedStatement实例来执行SQL语句,将被预编译并保存到PreparedStatement实例中,从而可以反复执行该语句。

代码如下:

package com.inba.maya.chaxun;

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

public class Text {
    public static void main1(String[] args) throws Exception{
        Scanner sc=new Scanner(System.in);
        System.out.print("请输入用户名:");
        String yhm=sc.nextLine();
        System.out.print("请输入密码:");
        String mm=sc.nextLine();
        YanZheng(yhm, mm);
    }


    private static void YanZheng(String yhm, String mm) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK","root","");
String s
="select * from user where username=? and pasword=?";
     PreparedStatement ps
=conn.prepareStatement(s); ps.setString(1, yhm); ps.setString(2, mm); ResultSet rs=ps.executeQuery();
if(rs.next()==true){ System.out.println("登陆成功,欢迎"+rs.getString(3)); }else{ System.out.println("对不起,您输入的用户名或密码不正确!"); } conn.close(); } }

 

转载于:https://www.cnblogs.com/AnswerTheQuestion/p/6249422.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值