1、createStatement()不能防止sql注入
public class TestJdbc {
public static void main(String[] args) throws Exception{
String url = "jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
Statement statement = connection.createStatement();
String sql1 = "select * from jdbc.persons";
ResultSet rs = statement.executeQuery(sql1);
while(rs.next()){
System.out.println("id:"+rs.getObject("id"));
System.out.println("name:"+rs.getObject("name"));
System.out.println("password:"+rs.getObject("password"));
System.out.println("email:"+rs.getObject("email"));
System.out.println("birthday:"+rs.getObject("birthday"));
}
rs.close();
statement.close();
connection.close();
}
}
2、prepareStatement(sql)可以防止sql注入
public class TestJdbc2 {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
Statement statement = connection.createStatement();
String sql = "insert into jdbc.persons (id, name, password, email, birthday) VALUES (?,?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,5);
preparedStatement.setObject(2,"赵六");
preparedStatement.setObject(3,"123454");
preparedStatement.setObject(4,"zl@qq.com");
preparedStatement.setObject(5,"2000-5-1");
int execute = preparedStatement.executeUpdate();
System.out.println(execute);
preparedStatement.close();
statement.close();
connection.close();
}
}