【JDBC】预处理查询,防止SQL注入的利器

简介: 1.JDBC - SQL注入问题Statement在实际使用的时候会引发sql注入的问题,因此我们在开发时常用PreparedStatement(预处理)或者CallableStatement(存储过程)来代替Statement


1.JDBC - SQL注入问题


Statement在实际使用的时候会引发sql注入的问题,因此我们在开发时常用PreparedStatement(预处理)或者CallableStatement(存储过程)来代替Statement


2.预处理查询


预处理的好处:


减少语法错误,不再频繁使用➕进行拼接语句

有效的解决了sql注入的问题

大大减少了编译次数,效率较高

在相关的Connection对象关闭之后,PreparedStatement对象也就变得无效了。不过,许多数据库通常都会自动缓存预备语句。如果相同的查询被预备两次,数据库通常会直接重用查询策略。因此,无需过多考虑调用prepareStatement的开销🧧


示例代码:使用PreparedStatement预处理sql语句以预防sql注入行为🧂


import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
/**
 * sql预处理方案
 */
public class PreparedStatementTest {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        // 问号相当于占位符
        String sql = "select id,username,password,school from user where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 给问号赋值
        preparedStatement.setInt(1,1);
        // 拿到结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        // 循环取出数据
        while (resultSet.next()) {
            int id = resultSet.getInt(1);
            String username = resultSet.getString(2);
            String userPassword = resultSet.getString(3);
            String school = resultSet.getString(4);
            System.out.println(id + "\t" + username + "\t" + userPassword +
                    "\t" + school);
        }
        // 关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}


3.JDBC - CRUD


示例代码:使用PreparedStatement来进行CRUD操作


import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
/**
 * sql预处理方案
 */
public class PreparedStatementTest {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        // 问号相当于占位符
        String sql = "select id,username,password,school from user where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 给问号赋值
        preparedStatement.setInt(1,1);
        // 拿到结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        // 循环取出数据
        while (resultSet.next()) {
            // 也可以通过列名来获取值,例如:
            // int id = resultSet.getInt("id");(推荐!!!)
            int id = resultSet.getInt(1);
            String username = resultSet.getString(2);
            String userPassword = resultSet.getString(3);
            String school = resultSet.getString(4);
            System.out.println(id + "\t" + username + "\t" + userPassword +
                    "\t" + school);
        }
        // 添加数据
        String sqlAdd = "insert into user values(?,?,?,?)";
        PreparedStatement preparedStatement1 = connection.prepareStatement(sqlAdd);
        preparedStatement1.setInt(1,6);
        preparedStatement1.setString(2,"zhiquan");
        preparedStatement1.setString(3,"admin");
        preparedStatement1.setString(4,"长安大学");
        int rows = preparedStatement1.executeUpdate();
        System.out.println(rows > 0 ? "数据添加成功":"数据添加失败");
        // 修改数据
        String sqlUpdate = "update user set school = ? where id = ?";
        PreparedStatement preparedStatement2 = connection.prepareStatement(sqlUpdate);
        preparedStatement2.setString(1,"花海大学");
        preparedStatement2.setInt(2,2);
        int i = preparedStatement2.executeUpdate();
        System.out.println(i > 0 ? "数据更新成功":"数据更新失败");
        // 删除数据
        String sqlDel = "delete from user where id = ?";
        PreparedStatement preparedStatement3 = connection.prepareStatement(sqlDel);
        preparedStatement3.setInt(1,3);
        int i1 = preparedStatement3.executeUpdate();
        System.out.println(i1 > 0 ? "数据删除成功":"数据删除失败");
        // 关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
目录
相关文章
|
1月前
|
SQL 安全 数据库
如何在Django中正确使用参数化查询或ORM来避免SQL注入漏洞?
如何在Django中正确使用参数化查询或ORM来避免SQL注入漏洞?
141 77
|
26天前
|
SQL NoSQL Java
Java使用sql查询mongodb
通过MongoDB Atlas Data Lake或Apache Drill,可以在Java中使用SQL语法查询MongoDB数据。这两种方法都需要适当的配置和依赖库的支持。希望本文提供的示例和说明能够帮助开发者实现这一目标。
45 17
|
21天前
|
SQL Oracle 关系型数据库
如何在 Oracle 中配置和使用 SQL Profiles 来优化查询性能?
在 Oracle 数据库中,SQL Profiles 是优化查询性能的工具,通过提供额外统计信息帮助生成更有效的执行计划。配置和使用步骤包括:1. 启用自动 SQL 调优;2. 手动创建 SQL Profile,涉及收集、执行调优任务、查看报告及应用建议;3. 验证效果;4. 使用 `DBA_SQL_PROFILES` 视图管理 Profile。
|
28天前
|
SQL Java 数据库连接
【潜意识Java】MyBatis中的动态SQL灵活、高效的数据库查询以及深度总结
本文详细介绍了MyBatis中的动态SQL功能,涵盖其背景、应用场景及实现方式。
91 6
|
2月前
|
SQL 存储 人工智能
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
Vanna 是一个开源的 Python RAG(Retrieval-Augmented Generation)框架,能够基于大型语言模型(LLMs)为数据库生成精确的 SQL 查询。Vanna 支持多种 LLMs、向量数据库和 SQL 数据库,提供高准确性查询,同时确保数据库内容安全私密,不外泄。
379 7
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
|
2月前
|
SQL NoSQL Java
Java使用sql查询mongodb
通过使用 MongoDB Connector for BI 和 JDBC,开发者可以在 Java 中使用 SQL 语法查询 MongoDB 数据库。这种方法对于熟悉 SQL 的团队非常有帮助,能够快速实现对 MongoDB 数据的操作。同时,也需要注意到这种方法的性能和功能限制,根据具体应用场景进行选择和优化。
109 9
|
3月前
|
SQL Java
使用java在未知表字段情况下通过sql查询信息
使用java在未知表字段情况下通过sql查询信息
54 8
|
3月前
|
SQL 安全 PHP
PHP开发中防止SQL注入的方法,包括使用参数化查询、对用户输入进行过滤和验证、使用安全的框架和库等,旨在帮助开发者有效应对SQL注入这一常见安全威胁,保障应用安全
本文深入探讨了PHP开发中防止SQL注入的方法,包括使用参数化查询、对用户输入进行过滤和验证、使用安全的框架和库等,旨在帮助开发者有效应对SQL注入这一常见安全威胁,保障应用安全。
106 4
|
3月前
|
SQL 安全 前端开发
Web学习_SQL注入_联合查询注入
联合查询注入是一种强大的SQL注入攻击方式,攻击者可以通过 `UNION`语句合并多个查询的结果,从而获取敏感信息。防御SQL注入需要多层次的措施,包括使用预处理语句和参数化查询、输入验证和过滤、最小权限原则、隐藏错误信息以及使用Web应用防火墙。通过这些措施,可以有效地提高Web应用程序的安全性,防止SQL注入攻击。
97 2
|
3月前
|
SQL 监控 关系型数据库
SQL语句当前及历史信息查询-performance schema的使用
本文介绍了如何使用MySQL的Performance Schema来获取SQL语句的当前和历史执行信息。Performance Schema默认在MySQL 8.0中启用,可以通过查询相关表来获取详细的SQL执行信息,包括当前执行的SQL、历史执行记录和统计汇总信息,从而快速定位和解决性能瓶颈。
128 1