Steps to Run Your JDBC Program:
- Download the
MySQL JDBC driver
- Uncompress the file.
tar zxvf mysql-connector-java-2.0.14.tar.gz
- Copy mysql-connector-java-2.0.14.jar into $JAVA_HOME/jre/lib/ext
or set your CLASSPATH to the path where the JDBC driver is located.
For example, use
setenv CLASSPATH .:~/jar/mysql-connector-java-2.0.14.jar in C shell
or export CLASSPATH=:~/jar/mysql-connector-java-2.0.14.jarin Bourne
shell.
- Create the sample JDBC code (mysqljdbc.java) as shown in below.
- Compile it by javac mysqljdbc.java.
- Run it by java mysqljdbc.
Note: The environment is already set up for you to run, just use
source ~cs655/bin/settomcat.csh
if you are using the C Shell or
. ~cs655/bin/settomcat.sh if you are
using the Bourne Shell.
This is the JDBC code to access MySQL.
/*
* Java sample program - Mysqljdbc.java
*/
import java.sql.*;
public class mysqljdbc {
public static void main(String args[]) throws ClassNotFoundException,
IllegalAccessException, InstantiationException, SQLException
{
String dbs_url = "jdbc:mysql://localhost/cs655?user=cs655&password=abc123";
// load database interfac
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection(dbs_url); // database connection
Statement stmt = conn.createStatement(); // SQL statement
String sql_cmd = "SELECT * from Friend";
ResultSet res = stmt.executeQuery(sql_cmd); // Result Set
while (res.next()) {
System.out.println("First Name: " + res.getString(1));
System.out.println("Last Name: " + res.getString(2));
System.out.println("City: " + res.getString(3));
System.out.println("State: " + res.getString(4));
System.out.println("Age: " + res.getInt(5));
}
// Clean up after ourselves
res.close();
stmt.close();
conn.close();
}
}