预处理语句是Statement的一个稍微强大一点的版本,并且应该总是至少像Statement一样快速和容易处理。 预估报表可以被参数化

大多数关系数据库处理JDBC / SQL查询分为四个步骤:

解析传入的SQL查询 编译SQL查询 规划/优化数据采集路径 执行优化的查询/获取和返回数据

对于发送到数据库的每个SQL查询,Statement将始终执行上述四个步骤。预处理语句预先执行上述执行过程中的步骤(1)-(3)。因此,在创建准备语句时,会立即执行一些预优化。其效果是在执行时减轻数据库引擎的负载。

现在我的问题是:

“使用预准备报表还有其他好处吗?”


PreparedStatement是一种非常好的防御(但不是万无一失的),可以防止SQL注入攻击。绑定参数值是防止“小Bobby表”进行不必要访问的好方法。


没什么可补充的,

1 -如果你想在循环中执行查询(超过1次),由于你提到的优化,预处理语句可以更快。

2 .参数化查询是避免SQL注入的好方法。参数化查询只在PreparedStatement中可用。


PreparedStatement的优点:

Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches. Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)"); preparedStatement.setString(1, person.getName()); preparedStatement.setString(2, person.getEmail()); preparedStatement.setTimestamp(3, new Timestamp(person.getBirthdate().getTime())); preparedStatement.setBinaryStream(4, person.getPhoto()); preparedStatement.executeUpdate(); and thus don't inline the values in the SQL string by string-concatenating. preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email) VALUES ('" + person.getName() + "', '" + person.getEmail() + "'"); preparedStatement.executeUpdate(); Eases setting of non-standard Java objects in a SQL string, e.g. Date, Time, Timestamp, BigDecimal, InputStream (Blob) and Reader (Clob). On most of those types you can't "just" do a toString() as you would do in a simple Statement. You could even refactor it all to using PreparedStatement#setObject() inside a loop as demonstrated in the utility method below: public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException { for (int i = 0; i < values.length; i++) { preparedStatement.setObject(i + 1, values[i]); } } Which can be used as below: preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)"); setValues(preparedStatement, person.getName(), person.getEmail(), new Timestamp(person.getBirthdate().getTime()), person.getPhoto()); preparedStatement.executeUpdate();


不能在语句中使用clob。

And: (OraclePreparedStatement) ps


这样更容易阅读 您可以轻松地将查询字符串设置为常量


准备语句忽略SQL注入,提高了准备语句的安全性


语句接口执行不带参数的静态SQL语句

PreparedStatement接口(扩展Statement)执行预编译的带/不带参数的SQL语句

对于重复执行有效 它是预编译的,所以更快


They are pre-compiled (once), so faster for repeated execution of dynamic SQL (where parameters change) Database statement caching boosts DB execution performance Databases store caches of execution plans for previously executed statements. This allows the database engine to reuse the plans for statements that have been executed previously. Because PreparedStatement uses parameters, each time it is executed it appears as the same SQL, the database can reuse the previous access plan, reducing processing. Statements "inline" the parameters into the SQL string and so do not appear as the same SQL to the DB, preventing cache usage. Binary communications protocol means less bandwidth and faster comms calls to DB server Prepared statements are normally executed through a non-SQL binary protocol. This means that there is less data in the packets, so communications to the server is faster. As a rule of thumb network operations are an order of magnitude slower than disk operations which are an order of magnitude slower than in-memory CPU operations. Hence, any reduction in amount of data sent over the network will have a good effect on overall performance. They protect against SQL injection, by escaping text for all the parameter values provided. They provide stronger separation between the query code and the parameter values (compared to concatenated SQL strings), boosting readability and helping code maintainers quickly understand inputs and outputs of the query. In java, can call getMetadata() and getParameterMetadata() to reflect on the result set fields and the parameter fields, respectively In java, intelligently accepts java objects as parameter types via setObject, setBoolean, setByte, setDate, setDouble, setDouble, setFloat, setInt, setLong, setShort, setTime, setTimestamp - it converts into JDBC type format that is comprehendible to DB (not just toString() format). In java, accepts SQL ARRAYs, as parameter type via setArray method In java, accepts CLOBs, BLOBs, OutputStreams and Readers as parameter "feeds" via setClob/setNClob, setBlob, setBinaryStream, setCharacterStream/setAsciiStream/setNCharacterStream methods, respectively In java, allows DB-specific values to be set for SQL DATALINK, SQL ROWID, SQL XML, and NULL via setURL, setRowId, setSQLXML ans setNull methods In java, inherits all methods from Statement. It inherits the addBatch method, and additionally allows a set of parameter values to be added to match the set of batched SQL commands via addBatch method. In java, a special type of PreparedStatement (the subclass CallableStatement) allows stored procedures to be executed - supporting high performance, encapsulation, procedural programming and SQL, DB administration/maintenance/tweaking of logic, and use of proprietary DB logic & features


语句将用于执行静态SQL语句,它不能接受输入参数。

PreparedStatement将用于多次动态执行SQL语句。它将接受输入参数。


语句是静态的,准备语句是动态的。

Statement适用于DDL, prepared Statement适用于DML。

语句较慢,而准备语句较快。

更多差异(存档)


PreparedStatement相对于Statement的一些好处是:

PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters. PreparedStatement allows us to execute dynamic queries with parameter inputs. PreparedStatement provides different types of setter methods to set the input parameters for the query. PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use it’s batch processing methods for executing multiple queries. PreparedStatement helps us in writing object Oriented code with setter methods whereas with Statement we have to use String Concatenation to create the query. If there are multiple parameters to set, writing Query using String concatenation looks very ugly and error prone.

阅读更多关于SQL注入问题,请访问http://www.journaldev.com/2489/jdbc-statement-vs-preparedstatement-sql-injection-example


不要混淆:只要记住

Statement is used for static queries like DDLs i.e. create,drop,alter and prepareStatement is used for dynamic queries i.e. DML query. In Statement, the query is not precompiled while in prepareStatement query is precompiled, because of this prepareStatement is time efficient. prepareStatement takes argument at the time of creation while Statement does not take arguments. For Example if you want to create table and insert element then :: Create table (static) by using Statement and Insert element (dynamic)by using prepareStatement.


准备查询或参数化查询的另一个特征:引用自本文。

该语句是数据库系统重复执行同一条SQL语句的高效特性之一。准备好的语句是模板的一种,由应用程序使用不同的参数。

语句模板准备好后发送给数据库系统,数据库系统对该模板进行解析、编译和优化,不执行即可存储。

有些参数,比如在以后的应用程序创建模板时没有传递子句,将这些参数发送给数据库系统,数据库系统使用SQL语句模板并按请求执行。

预处理语句对于SQL注入非常有用,因为应用程序可以使用不同的技术和协议来准备参数。

当数据数量不断增加,索引频繁变化时,Prepared statement可能会失败,因为在这种情况下需要一个新的查询计划。


引用自mattjames

语句在JDBC中的使用应该100%本地化为正在使用 对于DDL (ALTER, CREATE, GRANT等),因为这些是唯一的语句 不能接受BIND变量的类型。preparedstatement或 CallableStatements应该用于所有其他类型的语句 (DML、查询)。因为这些是接受bind的语句类型 变量。 这是一个事实,一条规则,一条法律——在任何地方都使用事先准备好的陈述。 几乎不使用语句。


我遵循了这个问题的所有答案,使用- Statement(但有SQL注入)将工作的遗留代码更改为使用PreparedStatement的解决方案,由于对Statement周围的语义理解不佳,代码要慢得多。addBatch(String sql) & PreparedStatement.addBatch()。

所以我在这里列出了我的情况,这样其他人就不会犯同样的错误。

我的设想是

Statement statement = connection.createStatement();

for (Object object : objectList) {
    //Create a query which would be different for each object 
    // Add this query to statement for batch using - statement.addBatch(query);
}
statement.executeBatch();

所以在上面的代码中,我有数千个不同的查询,都添加到相同的语句中,这段代码工作得更快,因为语句没有被缓存是好的&这段代码很少在应用程序中执行。

现在修复SQL注入,我把这段代码改为,

List<PreparedStatement> pStatements = new ArrayList<>();    
for (Object object : objectList) {
    //Create a query which would be different for each object 
    PreparedStatement pStatement =connection.prepareStatement(query);
    // This query can't be added to batch because its a different query so I used list. 
    //Set parameter to pStatement using object 
    pStatements.add(pStatement);
}// Object loop
// In place of statement.executeBatch(); , I had to loop around the list & execute each update separately          
for (PreparedStatement ps : pStatements) {
    ps.executeUpdate();
}

所以你看,我开始创建数千个PreparedStatement对象,然后最终不能利用批处理,因为我的场景要求-有数千个UPDATE或INSERT查询,所有这些查询碰巧是不同的。

在不降低性能的情况下修复SQL注入是强制性的,我认为在这种情况下使用PreparedStatement是不可能的。

另外,当你使用内置的批处理工具时,你必须担心只关闭一个语句,但使用这个List方法,你需要在重用之前关闭语句,重用一个PreparedStatement