解决SQL语句注入的安全漏洞
SQL注入是最简单的一种攻击 利用程序与服务器交互的过程(有输入的交互,注册,登陆等),将特殊字符传到数据库中,对数据库进行操作,就造成了SQL注入,现在SQL注入一般是没有机会的,因为这种方式很古老 这里使用PreparedStatement来解决SQL语句的注入问题
import java. sql. *;
public class JdbcTest {
public static void main ( String[ ] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class. forName ( "com.mysql.cj.jdbc.Driver" ) ;
conn = DriverManager. getConnection (
"jdbc:mysql://localhost:3306/db?serverTimezone=UTC" , "root" , "root" ) ;
String sql = "select *from user where id=?" ;
ps = conn. prepareStatement ( sql) ;
ps. setString ( 1 , "2" ) ;
rs = ps. executeQuery ( ) ;
while ( rs. next ( ) ) {
String id = rs. getString ( "id" ) ;
String user = rs. getString ( "user" ) ;
System. out. println ( id + " " + user) ;
}
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
try {
if ( rs != null) {
rs. close ( ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
try {
if ( ps != null) {
ps. close ( ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
try {
if ( conn != null) {
conn. close ( ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
}