Simple Database Access

The Connect example did not do much. It simply showed you how to connect to MySQL. A database connection is useless unless you actually talk to the database. The simplest forms of database access are SELECT, INSERT, UPDATE, and DELETE statements. Under the JDBC API, you use your database Connection instance to create Statement instances. A Statement represents any kind of SQL statement. Example 13-4 shows how to insert a row into a database using a Statement.

Example 13-4. Inserting a row into MySQL using a JDBC Statement object
import java.sql.*;
import java.util.*;

public class Insert {
    // We are inserting into a table that has two columns: TEST_ID (int)
    // and TEST_VAL (char(55))
    // args[0] is the TEST_ID and args[1] the TEST_VAL
    public static void main(String argv[]) {
        Connection con = null;
        ResourceBundle bundle = ResourceBundle.getBundle("SelectResource");

        try {
            String url = bundle.getString("URL");
            Statement stmt;

            Class.forName(bundle.getString("Driver"));
            // here is where the connection is made   
            con = DriverManager.getConnection(url, "user", "pass"); 
            stmt = con.createStatement(  );
            stmt.executeUpdate("INSERT INTO TEST (TEST_ID, TEST_VAL) " +
                               "VALUES(" + args[0] + ", '" + args[1] + "')");
        }
        catch( SQLException e ) {
            e.printStackTrace(  );
        }
        finally {
            if( con != null ) {
                try { con.close(  ); }
                catch( Exception e ) { }
            }
        }
    }
}

If this were a real application, we would of course verify that the user entered an INT for the TEST_ID, that it was not a duplicate key, and that the TEST_VAL entry did not exceed 55 characters. This example nevertheless shows how simple it is to perform an insert. The createStatement( ) method does just what it says: it creates an empty SQL statement associated with the Connection in question. The executeUpdate( ) method then passes the specified SQL on to the database for execution. As its name implies, executeUpdate( ) expects SQL that will modify the database in some way. You can use it to insert new rows, as shown earlier, or to delete rows, update rows, create new tables, or do any other database modification.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset