Last time, we have successfully retrieved a value from the database by calling the executeQuery in the Statement object and make use of the ResultSet object to store the returned values. so how about insert, update and delete?
Updater.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Updater {
public static void main(String[] args) {
System.out.println("*** Start ***");
// Set the JDBC driver and database driver path
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/spain";
// Set the database username and password
String user = "<username>";
String password = "<password>";
// Create the SQL statement
StringBuilder sb = new StringBuilder("");
sb.append("INSERT INTO cities (city_id, city_name) ");
sb.append("VALUES (101, 'Madrid'); ");
sb.append("INSERT INTO cities (city_id, city_name) ");
sb.append("VALUES (102, 'Valencia'); ");
// Load the JDBC driver
try {
Class.forName(driver);
} catch(Exception E) {
System.out.println("Unable to load JDBC driver: " + driver);
}
// Execute the SQL statement
try {
Connection con = DriverManager.getConnection(url,user,password);
Statement smt = con.createStatement();
smt.executeUpdate(sb.toString());
smt.close();
con.close();
} catch(SQLException SE) {
System.out.println("Fail to execute the SQL statement");
}
System.out.println("*** End ***");
}
As you can see from the above example, ResultSet is not needed and executeUpdate is called instead of executeQuery. Update and Delete SQL statements are also applicable in the above example.
