MySQL JDBC Driver. Connect to MySQL from Java

April 28, 2008 at 7:25 am Leave a comment

Although the majority of my programming efforts evolve around C# & ASP.NET using C#, I find myself doing more stuff with Java. As with every new language that I work with, there are specific things which are common across all languages, such as reading flat files and parsing delimited strings, reading and writing XML files and of course, connecting to a database that I tend to focus on.

The other day, I found myself needing to connect to a MySQL Database, so I downloaded the JDBC Driver (jar file) that would enable me to connect a small java app and read some data. I downloaded it from the java web site, you can do a search for “download jdbc drivers” and you should find the url.

Next, I created a new project in Eclipse and added a .java file. Be sure to add the .jar file for the jdbc driver to the build path of your Eclipse project or you will get an error when you try use the DriverManager and try to connect to the database.

Here is the code that I used:

Add the following import statement:
import java.sql.*;

Add the following module level variables. 

   static Connection conn;
   static Statement stmt;
   static ResultSet rset;

try {
   conn = DriverManager.getConnection(
   yourdatabase”, “loginid”, “loginpw”);

   rset = stmt.executeQuery(”SELECT *
        FROM ssfsigma.csaccount”);

   while( {
     System.out.println(rset[1].getString() );
catch( Exception ex ) {


Using the DriverManager object, I call the getConnection() method. The Statement is like the SqlCommand object, so I call CreateStatement() on the Connection object. Once I have my Statement, I create a ResultSet by using the executeQuery() method. After this, I can read each record in the ResultSet using the .next() method.

Notice that the connection string contains localhost:3306. This is the port that is defaulted in the install of MySQL.


Entry filed under: Database. Tags: , , .

How to collapse and expand rows of a datagrid using C#, ASP.NET, and Javascript. Write files in Java using BufferedWriter class

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

April 2008
    Jun »

%d bloggers like this: