这个坑比较恶心,一般数据小的时候不容易发现,如果你用SqlServer可以参考看看
JDBC使用PreparedStatement 的问号传参方式默认会不走索引,导致查询非常慢,但查询分析器直接查就很快,貌似是传参的编码引起的:
确定是以Unicode还是以数据库的默认字符编码方式将字符串参数发送到SQL Server数据库。这会严重影响SQL Server 2000的性能,因为它不会自动转换类型(如7.0所示),这意味着如果索引列是Unicode并且字符串是使用默认字符编码提交的(或以其他方式)SQLServer将执行索引扫描而不是索引查找。对于Sybase,确定在服务器的字符集中不能编码的字符串是否作为unicode字符串发送。编码逻辑的性能受到影响,因此如果unitext或univarchar数据类型未使用或者charset为utf-8,则将此选项设置为false
解决方法:在jdbc-url上加上 ;sendStringParametersAsUnicode=false
jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test;sendStringParametersAsUnicode=false
也可以用传参的方式加上
Class.forName(DRIVER_CLASS_NAME);Properties info = new Properties();info.put("user", USERNAME);info.put("password", PASSWORD);info.put("sendStringParametersAsUnicode", "false");conn = DriverManager.getConnection(URL, info);
以上是最简单的解决方案,看网上也有说改变字段类型,varchar -> nvarchar ,没试过,不懂是否有效
官方文档介绍:
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.