My problem, concerning prepared statements in java:
SELECT TrackingId FROM table where TrackingId = 5735053
TrackingId is an integer column in the database. Whe i change the query to:
SELECT TrackingId FROM table where TrackingId = '5735053'
it works fine as he converts it automaticly. Same goes to this query:
SELECT TrackingId FROM table where TrackingId LIKE '%5735%'
This works fine and the database is finding results. In java i want to pass the input value of the user to the query. It works with String and the like statement but not with int:
String query = "SELECT AnyString FROM table where AnyString like ?";
connectDatabase();
pstmt = connection.prepareStatement(query);
pstmt.setString(1, "%"+input+"%");
result = pstmt.executeQuery();
Now i want to pass an Integer through this statement and i have tried many things but always 0 results. So this won't work:
String query = "SELECT AnyInt FROM table where AnyInt like ?";
connectDatabase();
pstmt = connection.prepareStatement(query);
pstmt.setString(1, "%"+input+"%");
result = pstmt.executeQuery();
But if i type the query in my database programm it works fine and he is finding results. Can anybody help me with this here?
You can cast the field to varchar: cast(AnyInt as varchar)
. The reason it works as a literal is that then SQL Server knows it is a comparison between int and string and will automatically coerce the int to string. However when you use a parameter, the parameter has the same type as the column: int, so the value %<somenumber>%
is not a valid value (although I'm surprised that you don't get an exception).
Another option might be to cast the parameter: cast(? as varchar)
. I am not 100% sure casting the parameter is supported by SQL Server.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.