This section describes how to update existing data rows with UPDATE statements.
UPDATE statements are also commonly used by database applications when using users making changes to field values on the UI.
An UPDATE statements should have a SET clause to provide a list of columns with new values and
a WHERE clause to identify the rows to be updated.
UPDATE statements should be executed with the executeUpdate() method.
The Java tutorial program below shows you how to update
/**
* UpdateRows.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class UpdateRows {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
Statement sta = con.createStatement();
// updating multiple rows
int count = sta.executeUpdate(
"UPDATE Herong.Profile SET LastAccessDate = '2007-04-01'"
+ " WHERE UserID > 6");
System.out.println("Number of rows updated: "+count);
// getting the data back
ResultSet res = sta.executeQuery(
"SELECT * FROM Herong.Profile");
System.out.println("List of Profiles: ");
while (res.next()) {
System.out.println(
" "+res.getInt("UserID")
+ ", "+res.getString("FirstName")
+ ", "+res.getString("LastName")
+ ", "+res.getDate("LastAccessDate"));
}
res.close();
sta.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
The output confirms that 5 rows were updated with a new date in the LastAccessDate column: