JDBC03 Statement接口

Statement接口

用于执行静态SQL语句并返回它所生成结果的对象

三种Statem类

Statement:由createStatement创建,用于发送简单的SQL语句(不带参数的),会有SQL注入的风险

PreparedStatement:继承自Statement接口,由prepareStatement创建,用于发送含有一个或多个输入参数的sql语句。PreparedStatement对象比Statement对象的效率高,并且可以防止SQL注入

CallableStatement:继承自PreparedStatement,由方法prePareCall创建,用于调用存储过程

常用方法Statement方法:

execute():运行语句,返回是否由结果集

executeQuery():运行select语句,返回ResultSet结果集

executeUpdate():运行insert/update/delete操作,返回更新的行数

测试Statement及SQL注入

try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //建立连接:非常耗时,真正开发中使用连接池管理连接
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc?&useSSL=false&serverTimezone=UTC"
                    ,"root","***");
            Statement sts=conn.createStatement();
//            String sql="insert into t_user (username,pwd,regTime) values ('赵六',666666,now())";
//            sts.execute(sql);
            //测试SQL注入
            String id="5 or 1=1";
            String sql="delete from t_user where id="+id;
            sts.execute(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自www.cnblogs.com/code-fun/p/11411926.html
今日推荐