首页 > 技术文章 > 使用PreparedStatement接口操作数据库

wxbblogs 2017-06-10 21:53 原文

从代码来看,用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无论从可读性还是可维护性上来说,都比直接用Statement的代码高很多档次。

传递给PreparedStatement对象的参数可以被强制进行类型转换,使开发人员可以确保在插入或查询数据时与底层的数据库格式匹配。
在公共web站点环境下,有恶意的用户会利用那些设计不完善的、不能正确处理字符串的应用程序来个SQl注入,使用PreparedStatement安全性更高。

package cn.bdqn.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo3 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root", "0000");
System.out.println(conn);
pstmt = conn.prepareStatement("select * from student where StudentName=? and LoginPwd=?");
pstmt.setString(1, "郭靖");
pstmt.setString(2, "111111");
rs = pstmt.executeQuery();
while(rs.next()){
//查询获取字段值

}
} catch (Exception e) {
e.printStackTrace();
}finally{
//释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
pstmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}

推荐阅读