PreparedStatement对象
Posted saxon宋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PreparedStatement对象相关的知识,希望对你有一定的参考价值。
PreparedStatement对象
-
使用preparedStatement对象,可以有效的防止SQL注入,并且效率更高
-
新增
import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Date; public class Test01 { 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); //手动赋值参数 st.setInt(1,5); st.setString(2,"saxon"); st.setString(3,"123456"); st.setString(4,"sssssssssss@qq.com"); //获得时间戳 new Date().getTime() st.setDate(5,new java.sql.Date(new Date().getTime())); //执行 int i = st.executeUpdate(); if(i>0){ System.out.println("插入成功"); } } catch (Exception e) { e.printStackTrace(); } } }
-
删除
import java.sql.Connection; import java.sql.PreparedStatement; public class Test01 { public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; try { conn = jdbcUtils.getConnection(); String sql = "delete from users where id = ?"; st = conn.prepareStatement(sql); //手动赋值参数 st.setInt(1,5); //执行 int i = st.executeUpdate(); if(i>0){ System.out.println("删除成功"); } } catch (Exception e) { e.printStackTrace(); } } }
-
修改
import java.sql.Connection; import java.sql.PreparedStatement; public class Test01 { public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; try { conn = jdbcUtils.getConnection(); String sql = "update users set `name` = ? where id = ?"; st = conn.prepareStatement(sql); //手动赋值参数 st.setString(1,"xon"); st.setInt(2,1); //执行 int i = st.executeUpdate(); if(i>0){ System.out.println("修改成功"); } } catch (Exception e) { e.printStackTrace(); } } }
-
查询
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Test01 { public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = jdbcUtils.getConnection(); // PreparedStatement 防止SQL注入的本质,把传递进来的参数当作字符串 // 假设其中存在转义字符,就直接忽略, 比如说 \' 会被直接转义 String sql = "select * from users where `id` = ? "; st = conn.prepareStatement(sql); st.setInt(1, 1); rs = st.executeQuery(); // 查询完毕会返回一个结果集 while (rs.next()) { System.out.println(rs.getString("NAME")); System.out.println("====================="); } } catch (Exception e) { e.printStackTrace(); } } }
以上是关于PreparedStatement对象的主要内容,如果未能解决你的问题,请参考以下文章
Java_JDBC使用Statement和PreparedStatement