PreparedStatement和Statement的区别

使用Statement的时候:

Class.forName(driver);

conn = DriverManager.getConnection(url, username, password);

stmt = conn.createStatement();       //没有预编译sql

String sql;

sql="select * from stu_info";

ResultSet rs = stmt.executeQuery(sql);   //传入sql语句

 

使用PreParedStatement的时候:

Class.forName("com.mysql.jdbc.Driver");

String sql = "update book set bookCount=? where id=?";

Connection conn = DriverManager.getConnection(url,username,password);

PreparedStatement ps = conn.prepareStatement(sql);   //连接数据库时候预编译sql语言

ps.setInt(1, bookCount);

ps.setInt(2, id);

ps.executeUpdate();//不需要再传入sql

ps.close();

conn.close();

 

可以看出PreparedStatement在连接数据库的时候会预编译sql语言,所以执行多条sql语句时效率会高很多。并且PreparedStatement可以使用占位符。最重要的是极大地提高了安全性,防止类似于 select * from tb_name = '随意' and passwd = ' ' or '1' = '1';的恶意sql语法。执行一条sql语句时,Statement效率高

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章