对PostgreSQL的prepared statement的深入理解
看官方文檔:
http://www.postgresql.org/docs/current/static/sql-prepare.html
PREPARE creates a prepared statement. A prepared statement is a server-side object that can be used to optimize performance. When the PREPARE statement is executed, the specified statement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued, the prepared statement is planned and executed. This division of labor avoids repetitive parse analysis work, while allowing the execution plan to depend on the specific parameter values supplied.各自負責的階段
Prepare: parse--> analyze-->rewritten ? ?Prepare負責 構造語法樹,執(zhí)行一次。
Execute: plan-->Execute ?負責生成執(zhí)行計劃和執(zhí)行,這個步驟每次都要執(zhí)行。
Prepared statements can take parameters: values that are substituted into the statement when it is executed. When creating the prepared statement, refer to parameters by position, using $1, $2, etc. A corresponding list of parameter data types can optionally be specified. When a parameter's data type is not specified or is declared as unknown, the type is inferred from the context in which the parameter is used (if possible). When executing the statement, specify the actual values for these parameters in the EXECUTE statement. Refer to EXECUTE for more information about that.Prepared statement 可以帶參數(shù),也可以不帶參數(shù)。
Prepared statements only last for the duration of the current database session. When the session ends, the prepared statement is forgotten, so it must be recreated before being used again. This also means that a single prepared statement cannot be used by multiple simultaneous database clients; however, each client can create their own prepared statement to use. Prepared statements can be manually cleaned up using the DEALLOCATE command.Prepared statement 在PostgreSQL中是session 單位的。
a single prepared statement cannot be used by multiple simultaneous database clients
何時使用 prepared statement 比較有利:
Prepared statements have the largest performance advantage when a single session is being used to execute a large number of similar statements. The performance difference will be particularly significant if the statements are complex to plan or rewrite, for example, if the query involves a join of many tables or requires the application of several rules. If the statement is relatively simple to plan and rewrite but relatively expensive to execute, the performance advantage of prepared statements will be less noticeable.最有利的情況是:
When a single session is being used to execute a large number of similar statements.
最不利的情況是:
如果語句的 parse/analyze/rewritten 時間耗費很少,而plan和 execute 的時間耗費很大,則prepares statment 不一定有什么明顯效果。
轉載于:https://www.cnblogs.com/gaojian/p/3142096.html
總結
以上是生活随笔為你收集整理的对PostgreSQL的prepared statement的深入理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 锁分区提升并发,以及锁等待实例
- 下一篇: 乌鲁木齐乌房蓝锦湾是毛坯房还是精装修?