0
点赞
收藏
分享

微信扫一扫

博客_JDBC04_Statement

cwq聖泉寒江2020 2022-05-03 阅读 30

Statement基本介绍

1.Statement对象,用于执行静态SQL语句并返回其生成的结果的对象

2.在连接建立后,需要对数据库进行访问,执行命令或是SQL语句,可以通过

①Statement [现在不建议使用了,因为Statement对象执行SQL语句,存在SQL注入风险]

②PreparedStatement [叫:预处理,是Statement的子接口] (现在基本上都是用这个)

③CallableStatement [存储过程]

3.什么叫SQL注入:SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。

如:Select * from admin where name = ' 1 ' OR ' AND pwd ' OR '1' = '1'

4.要防范SQL注入,用PreparedStatement代替Statement就行

比如我下面的这个代码:


import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

public class PreparedStatement_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入学生学号:");
        String Sno=scanner.nextLine();
        System.out.println("请输入学生姓名:");
        String Sname=scanner.nextLine();
        //连接数据库
        Properties properties =new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //用getProperty()获取相关的值
        String url = properties.getProperty("url");
        String user= properties.getProperty("user");
        String password=properties.getProperty("password");
        String driver = properties.getProperty("driver");
        //1.注册驱动
        Class.forName(driver);
        //2.获得连接
        Connection connection = DriverManager.getConnection(url,user,password);//网络连接

        //3.组织sql
        String sql="select Sname,Sno from s where Sno=? and Sname=?";
        //4.获得Statement对象
        PreparedStatement preparedStatement =  connection.prepareStatement(sql);
        preparedStatement.setString(1,Sno);
        preparedStatement.setString(2,Sname);
        //5.执行sql返回单个ResultSet对象
        ResultSet resultSet = preparedStatement.executeQuery();
        //6.用while 循环取出数据
        if (resultSet.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        //关闭
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}

这个时候呢:再使用万能密码可就不行了,也就是是很有效的预防了SQL注入的这个问题

举报

相关推荐

0 条评论