---
title: "PreparedStatement与Statement性能详细对比"
author: "LucasLee"
date: "2007-01-22T22:28:35Z"
tags: ["MySQL", "Oracle", "PostgreSQL", "SQL"]
slug: "preparedstatement-statement"
draft: false
lastmod: "2007-01-22T22:28:35Z"
id: 49292
url: "https://lucaslee.iteye.com/blog/49292"
---

我对PreparedStatement和Statement的性能测试了一下：  
 测试代码如下：

java 代码

 

01. Connection con = getOraConnection();
02. String sql = "select id,name from test where id=";
03. String tempSql;
04. int count = 1000;
05. long time = System.currentTimeMillis();
06. for (int i = 0; i &lt; count; i++) {
07. Statement st = con.createStatement();
08. tempSql=sql+(int) (Math.random() * 100);
09. st.executeQuery(tempSql);
10. st.close();
11. }
12. System.out.println("st cost:" + (System.currentTimeMillis() - time));
13. String psql = "select id,name from test where id=?";
14. time = System.currentTimeMillis();
15. for (int i = 0; i &lt; count; i++) {
16. int id=(int) (Math.random() * 100);
17. PreparedStatement pst = con.prepareStatement(psql);
18. pst.setBigDecimal(1, new BigDecimal(id));
19. pst.executeQuery();
20. pst.close();
21. }
22. System.out.println("pst cost:" + (System.currentTimeMillis() - time));
23. con.close();

test表很简单，id int，name varchar(50).  
对几种数据库和相应驱动程序进行测试，结果如下(ms)：  
oracle:        1235    1109  
MSSQL2000(JTDS):391    453  
MSSQL2000(MS):    453    640  
Mysql5:        391    891  
PostgreSQL8.1:   1078    1047  
结论：  
1.单并发情况下，oracle--PostgreSQL--MSSQL--MySQL的性能依次增高；  
2.MySQL不支持Prepared Statement特性，已在其驱动程序的文档中证实，所以在MySQL里使用 PreparedStatement的性能尤其低，可以比Statement慢一倍以上。  
而MSSQL2000下，PreparedStatement比Statement慢;  
Oracle,PostgreSQL对它的支持最好，使用PreparedStatement性能比Statement高。