Home > Articles > Data > Access

  • Print
  • + Share This
Like this article? We recommend

Using MySQL with Java/JDBC

In this section, you'll configure your environment so that you can use MySQL with Java servlets and JDBC. You'll write a stand-alone Java program to test this environment before moving on to working with servlets.

The following software is required:

Download and install the software in the order listed. Install the MySQL database software by unzipping the download to a temporary directory and running the standard included Windows setup.exe installation program. During installation, you'll be prompted only for the installation directory. To start the database, use the command <mysqlinstalldir>\bin\mysqld. From the system prompt, start the MySQL shell, <mysqlinstalldir>\bin\mysql, and enter the following commands to create a new table called Books with fields for title, price, and topics:

USE Test;
CREATE table Books (Title varchar(64), Price decimal(3,2), Topics varchar(64));

The Test database is created with no tables during MySQL installation. You can check that you created the Books tables correctly using the DESCRIBE command:

DESCRIBE Books;

Next you need to install the MM.MySQL JDBC driver. To do this, simply download the .jar file and include it in your Java CLASSPATH. First test this with a stand-alone Java application to test your installation and configuration. You'll need to add some sample data to the Books table and write a program to query the table. (Actually, the program can be used to query any table.)

To populate the Books table, enter the following commands in the MySQL shell:

INSERT into Books VALUES ( "Voice Application Development Using VoiceXML",
              59.95, "VoiceXML, ASR, TTS, Internet" );
INSERT into Books VALUES ( "WAP Development with WML and WMLScript",
              59.95, "WML, WAP, Internet" );

You can view the data these commands inserted into the table using the SELECT command:

SELECT * from Books;

This will describe a simple stand-alone JDBC Java application to query tables and test your JDBC and MySQL installations. The program will accept command-line parameters for hostname, database name, user, password, and a SQL query string. It will execute the query and output the following results:

SQLTestApp.java
import java.sql.*;
import java.lang.*;
import java.util.*;

class MySQLTest
{
 public static void main (String args [])
  throws SQLException, ClassNotFoundException
 {
  if (args.length != 5)
  {
    System.out.println("\nUsage: java MySQLTest <host> <database> <login>
                          <paswd> <query>");
    System.exit(1);
  }

  // Load the MySQL JDBC driver
  try
  {
   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  }
  catch( Exception e )
  {
   e.printStackTrace();
  }

  // Connect, query and report
  try
  {
   String DBHost  = args[0];
   String DBDb   = args[1];
   String DBUser  = args[2];
   String DBPasswd = args[3];
   String DBQuery = args[4];

   Connection conn = DriverManager.getConnection(
    "jdbc:mysql://" + DBHost + "/" + DBDb +
    "?user=" + DBUser + "&password=" + DBPasswd );

   // Create a Statement
   Statement stmt = conn.createStatement ();

   ResultSet rs = stmt.executeQuery ( DBQuery );
   ResultSetMetaData rsmd = rs.getMetaData();
   int numColumns = rsmd.getColumnCount();

   while (rs.next ())
   {
    for( int i = 1; i <= numColumns; i++ )
    {
     System.out.print( rs.getObject( i ) + "|" );
    }
    System.out.println();
   }
   conn.close();
  }
  catch( Exception e )
  {
   System.out.println( e.getMessage() );
  }
 }
}

To compile the program, enter the following command at the system prompt:

javac SQLTestApp.java

To execute the program, enter the following command at the system prompt:

java SQLTestApp localhost test "" "" "select * from Books"

The output should be the results of the query, which is the contents of your Books table. If this doesn't work, make sure that the MM.MySQL JDBC driver is in your CLASSPATH.

Now that you have run a Java JDBC application successfully, in the next section you'll use this background to write a servlet that accesses a database. But before you can start writing JDBC servlets, there's a final configuration step: getting the JRun servlet engine to work with the MySQL database.

Start the JRun Management Console (Start, Programs, JRun, JRun Management Console) and log in. On the left side of the console is a tree view of the configuration parameters. In both the Admin server and the default server, select the Java Settings page and change the CLASSPATH to add the MySQL .jar file. Finally, under the default server's JDBC data sources, use the wizard to add a new data source for the Test database. In using the wizard, the relevant settings (assuming that you used installation defaults) are as follows:

Name: jdbc:mysql://localhost/Test
URL: jdbc:mysql://127.0.0.1:3306/Test
  • + Share This
  • 🔖 Save To Your Account