JDBC PreparedStatement-是否可以使用相同的参数? [英] JDBC PreparedStatement - Using the same argument, is it possible?
问题描述
我正在使用插入或更新"查询,例如以下查询:
I'm using an "insert or update" query such as the one below:
String sql =
"INSERT INTO servlets (path, applicationId, startTime, numOfRequests, totalResponseTime, totalBytes)" +
"VALUES (?, ?, NOW(), 1, ?, ?)" +
"ON DUPLICATE KEY UPDATE numOfRequests = numOfRequests + 1, " +
"totalResponseTime = totalResponseTime + ?, totalBytes = totalBytes + ?";
我正在使用准备好的语句,并通过以下方式用相关的参数填充它:
I'm using prepared statements and fill it with the relevant arguments in the following manner:
statement = connection.prepareStatement(sql);
statement.setString(1, i_ServletModel.GetPath());
statement.setInt(2, i_ServletModel.GetApplicationId());
statement.setLong(3, i_RequestStats.GetResponseTime());
statement.setLong(4, i_RequestStats.GetBytes());
statement.setLong(5, i_RequestStats.GetResponseTime());
statement.setLong(6, i_RequestStats.GetBytes());
请注意,参数3与参数5完全相同,参数4与参数6完全相同,因为它们在上面的查询中需要相同的值.
Notice that argument 3 is exactly the same as argument 5 and argument 4 is exactly the same as argument 6 since they require the same value in the query above.
在查询或自变量填充方法中,有什么我可以更改的方法,以避免这种丑陋"的语法吗?
Is there anything I can change, either in the query or in the arguments filling methods to avoid such an "ugly" syntax?
推荐答案
使用局部变量,可以减少代码的丑陋程度和出错率.但是JDBC
不支持命名参数的缺点仍然存在.同一参数将再次出现多行.
Using a local variable, you can make the code less ugly and error-prone. But the shortcoming of JDBC
that it does not support named parameters still holds. There will be again multiple lines for the same parameter.
statement = connection.prepareStatement(sql);
long time = i_RequestStats.GetResponseTime();
long bytes = i_RequestStats.GetBytes();
statement.setString(1, i_ServletModel.GetPath());
statement.setInt(2, i_ServletModel.GetApplicationId());
statement.setLong(3,time);
statement.setLong(4, bytes);
statement.setLong(5, time);
statement.setLong(6, bytes);
这篇关于JDBC PreparedStatement-是否可以使用相同的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!