PrepareStatement对象
PrepareStatement 可以防止SQL注入,效率更好。
里面的一些封装类是用的上一篇博客:
https://blog.csdn.net/weixin_/article/details/
操作步骤:
1: 编写SQL 2:预编译 3:传递参数 4:执行
讯享网
1:新增:
讯享网public static void main(String[] args) {
Connection coon = null; PreparedStatement pre = null; try {
coon = jdbcUtils.getConnection(); //区别 //使用占位符 ? 代替参数 String sql = "INSERT into users (id,`NAME`,`PASSWORD`,email,birthday)VALUES(?,?,?,?,?)"; pre = coon.prepareStatement(sql);//预编译sql,先写sql ,然后不执行 //手动给参数赋值 pre.setInt(1,4); pre.setString(2,"hanshuo"); pre.setString(3,""); pre.setString(4,"@.com"); //注意点 sql.Date 数据库 Java.sql.Date(); // util.Date Java new.Date().getTime();获取时间戳; pre.setDate(5,new java.sql.Date(new Date().getTime())); //执行sql int i = pre.executeUpdate(); if (i>0){
System.out.println("插入成功."); } } catch (SQLException e) {
e.printStackTrace(); }finally {
jdbcUtils.release(coon,pre,null); } }
2:删除
public static void main(String[] args) {
Connection coon = null; PreparedStatement pre = null; try {
coon = jdbcUtils.getConnection(); //使用占位符 ? 代替参数 String sql = "DELETE FROM users WHERE id = ?"; pre = coon.prepareStatement(sql);//预编译,险些sql,然后不执行; //手动给参数赋值; pre.setInt(1, 4); //执行sql语句 int i = pre.executeUpdate(); if (i > 0) {
System.out.println("删除成功!"); } } catch (SQLException e) {
e.printStackTrace(); }finally {
jdbcUtils.release(coon,pre,null); } }
3:修改
讯享网public static void main(String[] args) {
Connection coon = null; PreparedStatement pre = null; try {
//连接数据库 coon = jdbcUtils.getConnection(); //预编译 先写sql语句 然后不执行; String sql = "update users set name = ? where id = ?"; pre = coon.prepareStatement(sql); //手动给参数赋值; pre.setString(1,"hanshuo"); pre.setInt(2,1); //执行 int i = pre.executeUpdate(); if (i > 0) {
System.out.println("更改成功!"); } } catch (SQLException e) {
e.printStackTrace(); }finally {
jdbcUtils.release(coon,pre,null); } }
4;查询
public static void main(String[] args) {
Connection coon = null; PreparedStatement pre = null; ResultSet res = null; try {
//连接数据库 coon = jdbcUtils.getConnection(); //先写sql语句 预编译, ,用占位符代替参数,不执行; String sql = "SELECT * FROM `users` WHERE id = ?";//编写sql pre = coon.prepareStatement(sql);//预编译 //手动给参数赋值 pre.setInt(1, 1);//传递参数 //执行sql语句; res = pre.executeQuery();//执行 while (res.next()) {
System.out.println("查询成功1" + res.getString("NAME")); } } catch (SQLException e) {
e.printStackTrace(); } finally {
jdbcUtils.release(coon, pre, res); } }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/54117.html