1.JDBC第一种SQL注入方式连接语法 以下是查询的,这种方式可以造成SQL注入。
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="1998";
Connection connection = DriverManager.getConnection(url, user, password);
String sql="select *from exam";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ArrayList<User> users = new ArrayList<>();
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double chinese = resultSet.getDouble("chinese");
double math = resultSet.getDouble("math");
double english = resultSet.getDouble("english");
User user1 = new User(id,name,chinese,math,english);
users.add(user1);
}
for (User u1 :
users) {
System.out.println(u1);
}
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}
重点:JBUtils工具类的提取
public class JUtilsTest {
private static String driver;
private static String url;
private static String user;
private static String password;
static{
try{
Properties pro = new Properties();
InputStream resourceAsStream = JUtilsTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
pro.load(resourceAsStream);
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConncetion(){
Connection connection=null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void release(ResultSet rs, Statement st,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
db.properties文件属性如下 driver=com.mysql.jdbc.Driver url= user=root password= 2.使用防止SQL注入方式PreparedStatement的处理方式
Connection conncetion = JUtilsTest.getConncetion();
PreparedStatement statement = null;
try {
String sql = "update exam set name ='我',chinese=1000,math=math-100,english=english-100 where id=?";
statement = conncetion.prepareStatement(sql);
statement.setInt(1,7);
int executeUpdate = statement.executeUpdate();
System.out.println(executeUpdate > 0 ? "插入数据成功" : "插入数据失败");
} catch (SQLException e) {
e.printStackTrace();
}
JUtilsTest.release(null, statement, conncetion);
3.事务处理(了解) rollback可以在例如转账的时候第一个进入缓存区的时候发生异常,进行异常的时候进行数据回滚。
|