人們都說用PReparedStatement會提高程序的性能。我在sqlserver下面試了一下,結(jié)果令我大吃一驚 。
connection.setAutoCommit(false);
pstmt = connection.prepareStatement(sql);
pstmt.setFetchSize(100);
pstmt.setString(1,"026011009004");
ResultSet rs = pstmt.executeQuery();
connection.commit();
做一個查詢竟然需要6秒多,在數(shù)據(jù)庫里數(shù)據(jù)很少的情況下很快的,但是數(shù)據(jù)庫表里面的記錄多到100萬的時候查詢真的很慢。一開始我懷疑是jdbc驅(qū)動的事情可是我換了一個sqlserver的jdbc驅(qū)動結(jié)果還是一樣。
當(dāng)向pstmt 設(shè)置int類型的參數(shù)時性能又正常了。
為什么設(shè)置string類型的時候會出現(xiàn)的?令我百思不得其解。
我查看sqlserver jdbc 驅(qū)動的文檔 發(fā)現(xiàn)里面有這么一個參數(shù):
SendStringParameters
AsUnicode
SendStringParametersAsUnicode={true false}. Determines
whether string parameters are sent to the SQL Server database in
Unicode or in the default character encoding of the database.
True means that string parameters are sent to SQL Server in
Unicode. False means that they are sent in the default encoding,
which can improve performance because the server does not need
to convert Unicode characters to the default encoding. You
should, however, use default encoding only if the parameter
string data that you specify is consistent with the default
encoding of the database.
The default is true
原來string型的參數(shù)傳到數(shù)據(jù)庫里面默認(rèn)是轉(zhuǎn)換成unicode的。
當(dāng)我把SendStringParameters 設(shè)置成false時,查詢的性能得到了巨大的提高,原來用6秒的查詢現(xiàn)在只需要16毫秒了。
問題解決了。
新聞熱點
疑難解答