java 连接mysql数据库方式汇总 占位符防注入

本文介绍了如何通过Java JDBC直接利用Properties对象连接数据库,省去Class.forName()步骤。重点讲解了预编译防止SQL注入的方法,并提到了使用占位符的优势。

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

jdbc:
简单示例
方法四:直接连class都不用写,这样得出的东西是什么很好奇就是只是不获取driver?
看源码后发现:

package java.sql.DriverManager;

Applications no longer need to explicitly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work withoutmodification.

所以最简单的方式为:
(p.getProperty(“user”)直接用user也行)
Connection conn = DriverManager.getConnection(url,p.getProperty(“user”),p.getProperty(“password”));
(当然可以的话还是加上Driver driver = Class.forName(com.mysql.cj.jdbc.Driver)毕竟免得有其他bug,因为他是从其他地方加载的。)

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

简单示例1:

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class Test2 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//        Driver driver = new com.mysql.cj.jdbc.Driver();
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        Properties p = new Properties();
        p.setProperty("password","123456");
        p.setProperty("user", "root");
        Connection conn = DriverManager.getConnection(url,p.getProperty("user"),p.getProperty("password"));
        PreparedStatement preparedStatement = conn.prepareStatement("delete from test where a<?");
        preparedStatement.setString(1,"990" );
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
        conn.close();
        System.out.println(i);
    }
}

SQL注入:将sql代码作为输入参数,传递到sql服务器解析并执行的一种攻击手法

预编译(preparedStatement,setString)为什么防注入的原因是:
因为预编译是会对你的对象加上‘’变成字符串。
https://blog.csdn.net/siwuxie095/article/details/79190856

  1. 语句进行了相关的转义

    数据库厂商实现时,进行了相关的操作。

    使用占位符时不要用关键字

    所以使用占位符时不要使用in and or等关键词,不会生效。(这也是防注入的原因)

  2. SQL已经预编译好了,然后替换中间的占位符,这个占位符在编译后就已经确定了它只是一个参数属性。因此,用注入的代码去替换占位符,这个SQL也不会再进行编译了,所以也达不到注入的目的。

后续待补充:

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值