connecting to a mysql database in java

Desova

Limp Gawd
Joined
Jun 24, 2002
Messages
467
i'm trying to connect to a remote mysql database (hosted on my website) through a standalone java app, havent found any tutorials on it yet but i've found some sample codes that i havent been able to get to work:

Code:
Connection connection = null;
    try {
        // Load the JDBC driver
        String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
        Class.forName(driverName);
    
        // Create a connection to the database
        String serverName = "localhost";
        String mydatabase = "mydatabase";
        String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url
        String username = "username";
        String password = "password";
        connection = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
        // Could not find the database driver
    } catch (SQLException e) {
        // Could not connect to the database
    }

any ideas, tutorials or working code samples out there?
 
i'm running it now but its giving the following ClassNotFound exception:

java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver

so is this a file i'll need to download and attach manually?
 
It just means that he could not find the driver. Make sure that the driver is in the classpath of the Virtual machine.
 
right, got the file (found it early and tried to just include the driver file with no joy)

how do i go about adding it to the java virtual machine thingy?
 
You need to either add it into your CLASSPATH environmental variable or explicitly state it while starting the JVM.

Classpath:
Code:
CLASSPATH='path/to/driver/file.jar

manually add it at start:
Code:
java.exe -classpath=path/to/driver/file.jar

Alternately, you can also put it in JAVA_HOME/jre/lib/ext/

--KK
 
right, theres 2 .jar files in the /lib/ dir, and theres plenty of .java files in /com/ and /org/ folders

so i add the jar files to the classpath, and copy the com and org files into the JAVA_HOME/jre/lib/ext/ dir?
 
no. you do only one or the other. Either put the jar file into the lib/ext/ folder

OR

put the jar file anywhere and set the classpath to point to the location of the jar file.

The reason is the the JVM will look first in all locations designated in the classpath. If it's not found there, the JVM will look in the lib/ext folder for the driver. So you do one or the other. Also, there's no need to unpackage the jar file. leave the driver package as a jar file.

--KK
 
Back
Top