// sample code from MM.MySql documentation // -- source: http://www.worldserver.com/mm.mysql/doc/mm.doc/book1.htm // -- modifications: slight formatting modifications // + change in the URL // + short additions from other sources // + encapsulation in a separate class // with separate methods // need to set the CLASSPATH to .\;C:\...\mm.mysql.jdbc-1.2b // Example 3-2. Obtaining a Connection from the DriverManager // Once the driver is registered, a Connection can be established. Obtaining // a Connection requires a URL for the database. This URL is constructed // using the following syntax, where items contained in sqaure brackets // are optional: // // jdbc:mysql://[hostname][:port]/dbname[?param1=value1][¶m2=value2]... // import java.sql.*; import LoadDriver; // Notice, do not import org.gjt.mm.mysql.* // or you will have problems! public class MySqlConnect { // return a mysql connection to database cs407_general // for user cs407 with password pswd public static Connection getMySqlConnection() { try { Connection c = DriverManager.getConnection( "jdbc:mysql://earth.ccsu.ctstateu.edu/" + "cs407_general?user=cs407&password=pswd" ); return c; } catch (SQLException e) { System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); return null; } } // connect() public static void main(String[] args) { Connection c; boolean isDriverLoaded = false; // load the MM.MySql JDBC driver isDriverLoaded = LoadDriver.load(); if( !isDriverLoaded ) return; System.out.println("JDBC Driver Loaded"); System.out.println(); // establish the connection c = getMySqlConnection(); if ( c == null ) return; System.out.println("Connection established"); // clean up after ourselves try { c.close(); } catch (SQLException e) { System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } } // main() } // class MySqlConnect