我正在使用"插入或更新"查询,如下所示:
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 + ?";
Run Code Online (Sandbox Code Playgroud)
我正在使用预准备语句,并以下列方式填充相关参数:
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());
Run Code Online (Sandbox Code Playgroud)
请注意,参数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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11013 次 |
| 最近记录: |