/******************************************************************** * Made by Daniel.Schneider@tecfa.unige.ch 1999 TECFA. * This is Freeware * * Java Tutorial JDBC Example adapted to MySQL * MM MySQL Driver Version -> http://www.worldserver.com/mm.mysql/ * At TECFA (UNIX) : source /local/env/java117.csh * setenv CLASSPATH /local/java/classes/mm-jdbc/mysql.jar:. * Other Sites: install the Driver * * WARNING: This example might NOT work as is. You need a username and password * * Updated Feb 2000 (fixed imports and killed type casts) *******************************************************************/ import java.sql.*; public class QueryCoffees { public static void main(String args[]) { // ---- configure this for your site String username = "nobody"; String password = null; // The URL that will connect to TECFA's MySQL server // Syntax: jdbc:TYPE:machine:port/DB_NAME String url = "jdbc:mysql://tecfa.unige.ch:3306/COFFEEBREAK"; // A canned query string String queryString = "SELECT COF_NAME, PRICE FROM COFFEES"; // ---- configure END // INSTALL/load the Driver (Vendor specific Code) try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { Connection con; Statement stmt; // Establish Connection to the database at URL with usename and password con = DriverManager.getConnection(url, username, password); System.out.println ("Ok, connection to the DB worked."); System.out.println ("Let's see can retrieve something with: " + queryString); // Create a Statement Object stmt = con.createStatement(); // Send the query and bind to the result set ResultSet rs = stmt.executeQuery(queryString); while (rs.next()) { String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n); } // Close resources stmt.close(); con.close(); } // print out decent error messages catch(SQLException ex) { System.err.println("==> SQLException: "); while (ex != null) { System.out.println("Message: " + ex.getMessage ()); System.out.println("SQLState: " + ex.getSQLState ()); System.out.println("ErrorCode: " + ex.getErrorCode ()); ex = ex.getNextException(); System.out.println(""); } } } }