JDBC防止SQL注入

JDBC防止SQL注入

1.PreparedStatement的应用

作用:1.预编译sql语句,效率高

2.安全,防止sql注入

3.可以动态的填充数据,执行多个同构的SQL语句

 

package com.qf.JDBC;
​
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
​
public class JDBC防注入 {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();//next遇到空格结束,nextline能读取空格
        System.out.println("请输入钱数:");
        String money = scanner.nextLine();
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获得数据库连接
        String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
        String name ="root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url,name,password);
​
        //执行sql语句
        //获得PreparedStatement对象,预编译Sql语句
        PreparedStatement preparedStatement = connection.prepareStatement("select * from accounts where name =? and money=?;");
        //每一个参数都有一个占位符?,在执行SQL语句之前,要给占位符赋值,占位符顺序从一开始
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,money);
        //执行sql语句,并接收结果
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            System.out.println("登录成功!");
        }else{
            System.out.println("登录失败!");
        }
    }
​
​
}

运行结果:

请输入用户名:
A
请输入钱数:
1000
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
登录成功!

 

posted on 2023-01-28 15:00  张铁蛋666  阅读(376)  评论(0编辑  收藏  举报

导航