java - 为什么PreparedStatement比Statement快很多?

标签 java oracle jdbc

几天前,我必须使用内存计算框架创建一些处理性能测试。因此,为了做到这一点,我需要一个大数据池,并根据各种性能测试逐步增加该数据池。

数据库是 Oracle,包含一个包含 22 个字段的表。该表需要从 100 万条记录逐渐填充到 1 亿条记录。

为了用 100 万填充表,我生成了随机测试数据并使用 java 语句将其插入到数据库中,这大约花费了 17 又 16 秒分钟。之后,我很快意识到填充 1 亿条记录的表将花费很长时间,因此我尝试使用PreparedStatement,因为我知道这会快一点......但差异是如此巨大,1 分 24 秒,我已经开始在网上搜索这背后的原因,并找到了一些原因,但在我看来,没有什么应该产生这种影响。

这是我发现的可以解释这种差异的内容: LINK

PreparedStatement 已预编译 在数据库中,访问计划也缓存在数据库中,这允许数据库执行使用准备好的语句编写的参数查询比普通查询快得多,因为它要做的工作更少。您应该始终尝试在生产 JDBC 代码中使用PreparedStatement 来减少数据库的负载。为了获得性能优势,值得注意的是仅使用 SQL 查询的参数化版本,而不是字符串连接。

但是 所有数据都是随机生成的,因此不应涉及预言机端的主要缓存。

最佳答案

Oracle 可能能够将查询计划缓存在语句缓存中;根据 Oracle® Database JDBC 开发人员指南 Implicit Statement Caching ,

When you enable implicit Statement caching, JDBC automatically caches the prepared or callable statement when you call the close method of this statement object. The prepared and callable statements are cached and retrieved using standard connection object and statement object methods.

Plain statements are not implicitly cached, because implicit Statement caching uses a SQL string as a key and plain statements are created without a SQL string. Therefore, implicit Statement caching applies only to the OraclePreparedStatement and OracleCallableStatement objects, which are created with a SQL string.

关于java - 为什么PreparedStatement比Statement快很多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27407501/

相关文章:

java - 带有 Oracle 数组 : ORA-01000: maximum open cursors exceeded 的 Spring StoredProcedure

java - 如何解决com.mysql.jdbc.exceptions.MySQLSyntaxErrorException : Table 'task4DB.tst' doesn't exist exceptions

java - 在 Java 应用程序中打开和返回数据库连接的最佳方式?

java - 通过 Java 获取创建和填充的 MSSQL 临时表的结果集

java - 只检查第一个和最后一个字符

java - 简单的 string.equals 工作不正确 - Java

java - 在 Java Web 应用程序中存储密码变量的不同方法?

python - super 集仪表板 - 动态更新

java - "Find common ancestor"的变体

sql - ORA-00917 在 sql 查询中转义撇号