我正在使用“插入或更新”查询,如下所示:
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 + ?";
我正在使用准备好的语句并按以下方式用相关参数填充它:
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 完全相同,因为它们在上面的查询中需要相同的值。
有什么我可以更改的,无论是在查询中还是在参数填充方法中,以避免这种“丑陋”的语法?
最佳答案
使用局部变量,您可以使代码不那么丑陋且不易出错。但是JDBC
不支持命名参数的缺点仍然存在。同一参数将再次出现多行。
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);
关于java - JDBC PreparedStatement - 使用相同的参数,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673599/