You are on page 1of 2

CS3431: Using JDBC to connect mySQL Database

1 Setup
Installing JDBC (MySQL Connector/J) Driver Download the JDBC driver (mySQL Connector/J, either .zip or .tar.gz) from http://www.mysql.com/downloads/api-jdbc-stable.html. You only need to unzip the "mysql-connector-java-3.0.9-stable-bin.jar" file and put it on ccc.wpi.edu. Setting the CLASSPATH setenv CLASSPATH directory/mysql-connector-java-3.0.9-stable-bin.jar. You can put this line in your .cshrc file to avoid setting the path each time you logon ccc.

2 Write Java Code


Below is a sample Java code: General Step: 1. Set up DB connection 2. Execute SQL statement executeUpdate for select statement, executeUpdate for DDL,DML statement 3. Free resources import java.sql.*; import java.util.*; import java.io.*; public class mySQLDB { public static void main(String[] args) { Connection conn=null; Statement stmt=null; try { // 1. Connect to database try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Conn = DriverManager.getConnection ("jdbc:mysql://mysql.wpi. edu /your_db_name? your_user_name&your_password); } catch (Exception ex) { System.out.println("SQLException: " + ex.getMessage()); }

// 2. Create select statement and resultset; stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * from a"); while (rs.next()) { // iterate through the result set and print result for column a1 System.out.println("a1 = " + rs.getString("a1")); } } catch (SQLException sqlEx) { System.out.println("Caught SQL Exception: " + sqlEx.toString()); } // 3. now close the statement and connection if they exist if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { System.out.println("Could not close: " + sqlEx.toString()); } } if (conn != null) { try { conn.close(); } catch (SQLException sqlEx) { System.out.println("Could not close: " + sqlEx.toString()); } } } } Compile: javac mySQLDB Execute: java classpath .:$CLASSPATH mySQLDB

You might also like