Re: how to connect Java Application to MySQL
Posted by: Mohamed Mansour
Date: December 22, 2005 08:35PM

You would need the connector J from mysql inorder for the linkage
http://dev.mysql.com/downloads/connector/j/3.1.html
This is a simple example...

The minmum imports which is needed for a simple application could be:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



You would then have to create a connection so place this within the class

private Connection sqlConnection;



To test if the driver is properly installed, you could add this function. This is for debugging purposes...

public void testDriver() throws Exception {
System.out.println("Initializing Server... ");
try {
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println(" Driver Found.");
} catch (ClassNotFoundException e) {
System.out.println(" Driver Not Found, exiting..");
throw (e);
}
}



And to connect to the database you do this, so then we have a returned the connection from the databases...:

public Connection getConnection(String host, String userDB, String passDB, String database) throws Exception {
String url = "";
try {
url = "jdbc:mysql://" + host + "/" + database;

Connection con = DriverManager.getConnection(url, userDB, passDB);
System.out.println(" Database connection established to " + url+ ".");

return con;
} catch (java.sql.SQLException e) {
System.out.println(" Connection couldn't be established to "+ url);
throw (e);
}
}



I believe thats an easy way to do it, read the docs:) they help tremendously.
Enjoy heh

This example is the easiest you can go... very simple the way I put it...

Now use the connection that is brought, and execute your queries... using the Connection API..

look up in the Java docs for Connection java.sql.Connection


Hope it helped

Mohamed Mansour
Software Engineer
Microsoft Student Partner Alumni

Options: ReplyQuote




Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.