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 usingClass.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, theDriverManager
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
-
语句进行了相关的转义
所以使用占位符时不要使用in and or等关键词,不会生效。(这也是防注入的原因)
-
SQL已经预编译好了,然后替换中间的占位符,这个占位符在编译后就已经确定了它只是一个参数属性。因此,用注入的代码去替换占位符,这个SQL也不会再进行编译了,所以也达不到注入的目的。
后续待补充: