JDBC拓展------PrepareStatement

PrepareStatement实现JDBC代码展示

import java.sql.*;

public class Main {//com.mysql.cj.jdbc.Driver
    private static final String URL="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
    private static final String USERNAME="yucan";
    private static final String PASSWORD="1234";

    public static void update(){  //增删改
        Connection connection=null;
        PreparedStatement pstatement=null;
        try{
            //a.导入驱动。加载具体的驱动类
            Class.forName( "com.mysql.cj.jdbc.Driver" );
            //b.建立连接
            connection=DriverManager.getConnection( URL,USERNAME,PASSWORD );
            //发送sql,执行
            String sql="insert into id values(?,?)";
            pstatement=connection.prepareStatement( sql );
            pstatement.setString( 1,"24" );
            pstatement.setString( 2,"21" );
            int count=pstatement.executeUpdate();
            //注意:这个地方不用添加参数sql
            if(count>0){
                System.out.println( "执行成功!" );
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                if(pstatement!=null)
                    pstatement.close();
                if(connection!=null)
                    connection.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        update();
    }
}

PrepareStatement是statement的子类
     相比较而言,两者的区别如下:
          1.相对来说更加快捷;
          2.可以方式sql注入

一.快捷
     由于preparestatement有预编译功能,所以,在多次执行相同的sql语句的时候,可以只执行,不编译,但是statement每次执行,都需要进行编译操作。
statement实例:
String sql=“insert into student (stuno,stuname) value(‘“+name+”’,"+age+")”;
statement.executeUpdate(sql);
PreparedStatement实例:
String sql=“insert into student (id,password) value(?,?)”;
preparestatement=connection.prepareStatement(sql); //预编译
prepareStatement.setInt(1,23);
preparestatement.setString(2,“dsfdfad”);

二.防止sql注入
statement:
          存在被sql注入的风险
(例如输入: 用户名:任意值‘ or 1=1-- 密码:任意值)
分析:
          select count(*) from login where uname=“任意值” or1=1 --’ and userpassword=’任意值‘                      这个表达式恒为真
Preparestatement
          可以有效地防止sql注入

发布了11 篇原创文章 · 获赞 0 · 访问量 162

猜你喜欢

转载自blog.csdn.net/yucan1234/article/details/104930764
今日推荐