Java + JDBC + MySQL = SWEET!

Posted on : December 8, 2001

by: Sassy
After a few weeks of struggling with sorting algorithms and other such crap, I realized my Java class was a dud. So one night I sit down and start looking at JDBC, and a few hours later, it was on. This has renewed my interests in Java, I will revisit it later. JDBC is a Java implementation of Microsoft’s ODBC, a Database API. ODBC is used to connect and query databases from multiple vendors through a standard API.

This program performs a pretty basic grab from a mysql table.

Setup is a little tricky, but not too bad. First download the JDBC Drivers for MySQL:http://mmmysql.sourceforge.net/. Extract it:

jar -xf mm.mysql-2.0.8-you-must-unjar-me.jar

On Windows, append or set your CLASSPATH environment variable to contain a path to the executable JAR file in the driver distribution, for example:

SET CLASSPATH=%CLASSPATH%;C:jdk1.3.1mm.mysql-2.0.8mm.mysql-2.0.8.jar

You will want to add the above line to your AUTOEXEC.BAT file.

Writing the program is pretty straightforward, and remarkably similar to other ODBC implementations.

import java.io.*;
import java.sql.*;

public class test {
public static void main (String[] args) {
try {
//this line loads the mysql driver. Make sure it is in CLASSPATH!
Class.forName(“org.gjt.mm.mysql.Driver”);
} catch (ClassNotFoundException ex){
//debug info
System.out.println(” ClassNotFoundException: !! “+ex.getMessage());
ex.printStackTrace();
System.exit(255);
}

try {
//JDBC-style connection string
Connection conn = DriverManager.getConnection
(“jdbc:mysql://hostname/dbname”);

//set the SQL,recordset,iterate
String sql = “SELECT * FROM catalog;”;
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(sql);
int i = 0;

while(res.next()) {
System.out.println(“#> Entry ” + i);
String r = res.getString(“CatalogName”);
System.out.println(“#> Name:” + r);
String s = res.getString(“CatalogComment”);
System.out.println(“#> Comment:” + s);
System.out.println(“”);
i++;
}

} catch(SQLException e) {
//debug info
System.out.println(“SQLException:”);
System.out.println(e.toString());
e.printStackTrace();
System.exit(255);
}

}

}
Felix
as
http://

Sounds like easy java to me. Inter-Nerd…


1337 B01
sd
http://

5KR1P7 K1DDY!!! LOL Just kidding. Sounds interesting. Your brain is getting more exercize than mine.


Leave a Reply