您可以改爲使用Statement.executeUpdate()。 因爲您需要將您的SELECT
聲明更改爲UPDATE聲明。
缺點是您無法訪問單行數據,因爲您根本沒有選擇它。如果你需要這個,例如要計算更新後的值(在您的情況下爲[email protected]<localipaddress>
),您可能必須首先按照您所做的操作選擇該選擇,然後在內存中計算您的更新,然後使用PreparedStatement或Batch Update執行UPDATE
報表。
預處理語句例如:
public static int preparedUpdate(Connection conn, String localIPAddress) throws SQLException {
int numChangedRows = 0;
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
while (rs.next()) {
// id => something unique for this row within the table,
// typically the primary key
String id = rs.getString("id");
String jid = rs.getString("column1");
if("abc".equals(jid)) { // just some nonsense condition
try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
batchUpdate.setString(1, localIPAddress);
batchUpdate.setString(2, id);
numChangedRows = batchUpdate.executeUpdate();
}
}
}
}
return numChangedRows;
}
批量更新例如:
public static int[] batchUpdate(Connection conn, String localIPAddress) throws SQLException {
int[] changedRows = null;
try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
while (rs.next()) {
// id => something unique for this row within the table,
// typically the primary key
String id = rs.getString("id");
String jid = rs.getString("column1");
if("abc".equals(jid)) { // just some nonsense condition
batchUpdate.setString(1, localIPAddress);
batchUpdate.setString(2, id);
batchUpdate.addBatch();
}
}
}
changedRows = batchUpdate.executeBatch();
}
return changedRows;
}
更新哪一行?所有的行?一些特定的行?更新哪些列? –
請發表表格定義 - 什麼是你更新updateString()的列類型?最好將代碼片段和異常跟蹤作爲文本(而不是圖片)發佈,幫助大G找到這篇文章。 – chrisinmtown