A Short Java Example
Listing F.1 takes three parameters on the command line, which it inserts into the customer table. Run it as follows:
% /usr/java/j2sdk1.4.1/bin/java InsertSelect 10 Leon Wyk
Listing F.1: InsertSelect.java
import java.sql.*;
import java.util.*;
// The insertRecord class does the bare minimum for inserting a record
// and also performs a skeleton level of exception handling
public class InsertRecord {
public static void main(String argv[]) {
Connection dbh = null;
ResultSet resultset;
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e) {
System.err.println("Unable to load driver.");
e.printStackTrace();
}
try {
Statement sth,sth2;
// connect to the database using the Connector/J driver
dbh = DriverManager.getConnection("jdbc:mysql://–
localhost/firstdb?user=mysql");
// instantiate the statement object, and run the query (an update query)
// the three argv[] fields come from the command line
sth = dbh.createStatement();
sth.executeUpdate("INSERT INTO customer(id,first_name,surname)–
VALUES(" + argv[0] + ", '" + argv[1] + "', '"+argv[2]+ "')");
sth.close();
// instantiate the statement object, and run the SELECT query
sth2 = dbh.createStatement();
resultset = sth2.executeQuery("SELECT first_name,surname FROM customer");
// loop through the result set, displaying the results
while(resultset.next()) {
String first_name = resultset.getString("first_name");
String surname = resultset.getString("surname");
System.out.println("Name: " + first_name + " " + surname);
}
sth2.close();
}
catch( SQLException e ) {
e.printStackTrace();
}
finally {
if(dbh != null) {
try {
dbh.close();
}
catch(Exception e) {}
}
}
}
}