关于preparedstatement接口
PreparedStatement也是用来执行sql语句的与创建Statement不同的是,需要根据sql语句创建PreparedStatement。其还能够通过设置参数,指定相应的值,而不是Statement那样使用字符串拼接。
其实就是Preparedstatement在外面拼接SQL语句的时候可以使用占位符来指定,相较于Statement,Preparedstatement的灵活性更高。
如何使用Preparedstatement接口
在使用此接口前,我们定义了一个DbUtil作为数据库处理类,具体实现如下
public Class DbUtils{
//1.定义工具类需要的对象
protected Connection conn=null;
protected PreparedStatement ps=null;
protected ResultSet rs=null;
protected int k=0;//受影响的行数
private driverName="com.mysql.cj.jdbc.Driver";
private url="jdbc:mysql://localhost:3306";
private userName=//输入你的数据库用户名(一般是root);
private password=//输入你的数据库密码;
//2.加载驱动
static{
try{
Class.forName(driverName);
}catch(ClassNotFoundException ex){
ex.printStackTrace();
}
}
//3.获得链接
protected Connection getConnection(){
try{
conn=DriverManger.getConnection(url,userName,password);
}catch(SQLException ex){
ex.printStackTrace();
}
return conn;
}
//4.创建通道
protected PreparedStatement getPst(String sql){
try{
getConnection();
ps=conn.preparedStatement(sql);
}catch(SQLException ex){
ex.printStackTrace();
}
return ps;
}
//5.给占位符赋值
protected void setParams(List list){
try{
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
ps.setObject(i+1,list.get(i));//赋值从参数1开始
}
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
//6.增删改调取的方法
protect int update(String sql,List params){
try{
getPst(sql);
setParams(params);
k=ps.executeUpdate();
}catch(SQLException ex){
ex.printStackTrace();
}
return k;
}
//7.查询的时候调取的方法
protected ResultSet query(String sql,List params){
try{
getPst(sql);
setParams(params);
rs=ps.executeQuery();
return rs;
}catch(SQLException ex){
ex.printStackTrace();
}
return null;
}
//8.关闭资源
protected void closeAll(){
try{
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
接下来我们就可以使用PreparedStatment进行SQL语句的预处理
· 下列代码在values后面使用了‘?’占位符
· 并且将参数courseName拼接到SQL语句中并执行操作
public void addCourse(String courseName){
String sql = "insert into t_course(course_name) values(?)";
//该语句为每个 IN 参数保留一个问号(“?”)作为占位符
Connection conn = DbUtil.getConnection();//连接数据库
PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, courseName); //给占位符赋值
pstmt.executeUpdate(); //执行
//省略trycatch、close处理(根据提示加上即可)
}
相较于Statment
Statment是需要在sql语句里面进行String对象的硬编码拼接,逻辑会麻烦许多
public void addCourse(courseName){
//拼接String
String sql="insert into t1(id) values ("+courseName+")";
Connection conn = DbUtil.getConnection();//连接数据库
Statement st = conn.createStatement();
st.executeUpdate(sql);
//省略trycatch、close处理(根据提示加上即可)
}
至此我们会发现相较于statement硬编码的SQL语句,PreparedStament简直是太灵活了!