SQL Server deadlock when using PreparedStatements

房东的猫 提交于 2020-02-15 10:12:10

问题


I have a java servlet application and I'm using a prepared query to update a record in a SQL Server Database table.

Lets say I want to execute UPDATE MyTable SET name = 'test' WHERE id = '10'. (Yes, id is a varchar)
I used the following code to make this happen:

PreparedStatement pstmt = con.prepareStatement("UPDATE MyTable SET name = ? WHERE id = ?");
pstmt.setString(1, getName() );
pstmt.setString(2, getID() );
pstmt.executeUpdate();

I found out that while I was running a JMeter script to simulate 2 users, this statement causes a deadlock in my database.

I wanted to check what my values were in the SQL Profiler so I used the following code, so I could check the values.

String query = String.format("UPDATE MyTable SET name = '%s' WHERE id = '%s' ", getName(), getID() );
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.executeUpdate();

Suddenly my deadlock was gone! It's a shame the last approach is vulnerable to SQL injection.

Is there somebody who can tell me what is going on and/or how to fix it?


回答1:


Ok I finally found the problem and solution to my problem.

It seemed that the combination of the jTDS JDBC driver with MSSQL was the 'problem'.

This article explained my situation exactly. And with the help of this FAQ I was able to set the datasource to the right configuration.

From what I understand:

If you have statement that uses a String-like index (Like in my situation), the table performs an index SCAN instead of an index SEEK. This causes the whole table to be locked and vulnerable to deadlocks.

I hope this will help other people too.



来源:https://stackoverflow.com/questions/24911333/sql-server-deadlock-when-using-preparedstatements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!