PreparedStatement:执行增删改,查
作者:互联网
1.1增删改
package com.king.lesson03; import com.king.lesson02.utils.JdbcUtils; import java.sql.Connection; import java.util.Date; import java.sql.PreparedStatement; import java.sql.SQLException; //PreparedStatement与Statement相比,效率更高,同时也解决了sql注入问题 public class InertTest { public static void main(String[] args) { Connection conn=null; PreparedStatement st=null; try { conn=JdbcUtils.getConnection(); //区别 //可使用?,占位符代替参数 String sql="INSERT INTO users(id,`NAME`,`PASSWORD`,email,birthday)" + "VALUES(?,?,?,?,?)"; st=conn.prepareStatement(sql);//需要预编译SQL,先写sql,然后不执行 //手动给参数赋值 st.setInt(1,5);//id st.setString(2,"kingss"); st.setString(3,"111111"); st.setString(4,"888888@qq.com"); //注意点:sql.date 数据库 Java.sql.Date() // util.Date Java new Date().getTime()获得时间戳 st.setDate(5,new java.sql.Date(new Date().getTime())); //执行 int i=st.executeUpdate();//i返回一个受影响的行数 if (i>0){ System.out.println("插入成功"); System.out.println(i); } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { JdbcUtils.release(conn,st,null); } } }
//注意:删,改操作跟insert操作相似,只需要修改sql语句,和手动参数赋值语句就可实现
注意:增删改的执行语句为:executeUpdate()
搜索的执行语句为:executeQuery()
1.2搜索语句
package com.king.lesson03; import com.king.lesson02.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SelectTest { public static void main(String[] args) { Connection conn=null; PreparedStatement st=null; ResultSet rs=null; try { conn=JdbcUtils.getConnection(); String sql="select * from users where id=?";//编写sql st=conn.prepareStatement(sql);;//预编译 st.setInt(1,1);//传递参数 rs=st.executeQuery();//执行 if (rs.next()){ System.out.println(rs.getString("NAME")); System.out.println(rs.getObject("birthday")); } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { JdbcUtils.release(conn,st,rs); } } }
标签:PreparedStatement,java,st,JdbcUtils,sql,增删,import,执行,conn 来源: https://www.cnblogs.com/CL-King/p/13757295.html