Java_jdbc 基础笔记之六 数据库连接 (PreparedStatement)

 

reparedStatement 是 Statement 的子接口 
* ①需要预编译 SQL 语句:PreparedStatement ps = conn.preparedStatement(sql); 
* ②填充占位符:setObject(int index);//index 从 1 开始 
* ③execute() / executeUpdate() ; executeQuery(); 返回一个 ResultSet 
* 
* 1.替换原来的 Statement,实现增删改和查的操作 –>Statement 的问题: 
* ①拼串 不方便,容易出错 
* ②存在 sql 注入的问题,可以对数据库进行恶意攻击。

 

 

@Test
    public void testPreparedStatement(){
            Connection conn=null;
            PreparedStatement ps=null;
            try {
                conn=JDBCTools.getConnection();
                //需要预编译SQL语句
                String sql="INSERT INTO customers (name,email,birth)VALUES(?,?,?)";
                ps=conn.prepareStatement(sql);
                //填充占位符
                ps.setString(1, "xiaohong");
                ps.setString(2, "xiaohong@atguigu");
                ps.setDate(3, new Date(new java.util.Date().getTime()));
                //调用方法
                ps.executeUpdate();
            } catch (Exception e) {
            e.printStackTrace();
            }finally{
                JDBCTools.close(null, ps, conn);
            }

 

 

 

 

转: https://blog.csdn.net/YL1214012127/article/details/48292825

 

posted @ 2019-12-11 17:08  与f  阅读(314)  评论(0编辑  收藏  举报