Java PreparedStatement .executeUpdate ()
Syntax
PreparedStatement.executeUpdate() has the following syntax.
int executeUpdate() throws SQLException
Example
In the following code shows how to use PreparedStatement.executeUpdate() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
// w w w .j a v a 2 s . co m
public class Main {
public static void main(String[] args) throws Exception {
try {
String url = "jdbc:odbc:databaseName";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "guest";
String password = "guest";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url,user, password);
String changeLastName = "UPDATE authors SET lastname = ? WHERE authid = ?";
PreparedStatement updateLastName = connection.prepareStatement(changeLastName);
updateLastName.setString(1, "Martin"); // Set lastname placeholder value
updateLastName.setInt(2, 4); // Set author ID placeholder value
int rowsUpdated = updateLastName.executeUpdate(); // execute the update
System.out.println("Rows affected: " + rowsUpdated);
connection.close();
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}