Simple Database Access

The Connect example did not do much. It simply showed you how to connect to a database. 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 naturally represents any kind of SQL statement. Example 14.4 shows how to insert a row into a database using a Statement.

Example 14-4. Inserting a Row into mSQL 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, "borg", ""); 
            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 verified that the user entered an INT for the test_id, that it was not ...

Get MySQL and mSQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.