How to Use MySQL with Java

Before we start the tutorial, we assume you know a little bit about java, like what Java classes are, and how to create methods etc.

Prerequesites:

  • You need a MySQL database that you can connect to.
  • JDBC driver for java that can be found here: http://dev.mysql.com/usingmysql/java/
  • Java SDK (1.5+) and a compiler.
  • Include the JDBC driver in your project.

Required file(s):

  • the database where this tutorial is based on (run the sql below to create one)
  • Java class: MainTest.java (attached blow)
  • Java class: ConnectToDatabase.java (attached below)

Recommended tools: Eclipse IDE, Java 1.5 or higher

So how do we make a connection to the MySQL database using Java?

To connect to a MySQL database (or any if that matters) you need to supply a username and password, so in ConnectToDatabase class, we created a method that takes 4 parameters such as a userName, userPassword, the database url and the sql query you want to execute.

This is the code in the method in the ConnectToDatabase class that will execute your queries:

  public void connect(String userName, String userPassword,
                           String databaseUrl, String userQuery)
  {
     try {
*       Class.forName ("com.mysql.jdbc.Driver").newInstance ();
*       Connection conn = DriverManager.getConnection (databaseUrl,
*                                  userName, userPassword);
*
*       Statement stat = conn.createStatement();
*       String query = userQuery;
*       ResultSet result = stat.executeQuery(query);

        System.out.println("Result(s): ");
#       while(result.next()){
#          System.out.println("Name:\t" + result.getString("userName"));
#          System.out.println("Hobby:\t" + result.getString("userHobby"));
#          System.out.println("");
#       }
        conn.close();
     }catch (SQLException e) {}
     catch (InstantiationException e) {}
     catch (IllegalAccessException e) {}
     catch (ClassNotFoundException e) {}
  }

Basically what this does is making the actual connection to the database and shows the result(s) on the screen.
(*) this part of the code creates the new “com.mysql.jdbc.Driver” instance and executes the query.
(#) in this loop the result(s) will be shown. If there are no results nothing will be displayed.

So how does my ConnectToDatabase class know where to connect and what query to perform? Well, the answer is simple. There is another class (MainTest class) that handles that. So now I’ll explain what the MainTest class does.

The code in the main class from the class “MainTest” looks like this:

  ConnectToDatabase CTD = new ConnectToDatabase();
  CTD.connect(userName, userPassword, databaseUrl, userQuery);

The first line is to make an instance of the ConnectToDatabase class created especially for this tutorial. Then in the second line, we call the connect method from ConnectToDatabase and pass the arguments we have in the main class to the public variables.

Let’s say we try to login with something like this:

  static String userName = "root";
  static String userPassword = "";
  static String databaseUrl =
      "jdbc:mysql://localhost:3306/EngineeringserverDotComTest";
  static String userQuery = "select * from info";

Compile the MainTest and ConnectToDatabase classes and make sure your settings are correct. If everything is correct you should see some result(s). That’s it, I hope you enjoyed this tutorial.

Download the sample codes:


Related Blog Posts:


2 Comments »

Please help me , i tried this program , i’ve done all the prerequisites , but showing driver error , i’m using ubuntu , i need to know any settings to be done , heard something about classpath .. All Other java programs are working except database connectivity

os : ubuntu 8.10
mysql :mysql Ver 14.12 Distrib 5.0.67
mysqlconnector : 1.7
java :1.6 version

Please give me advice ..

Comment by Vibin Lakshman — February 14, 2009 @ 9:31 am

Note that having catch (..) {} (i.e. without doing anything at all when an exception is thrown) is very bad practice. If there is any error whatsoever you will be unable to see it, and it will be next to impossible to see why.

Still very easy but mucch better would be something to the effect of:

catch (Exception e){
System.err.println(e);
e.printStackTrace();
System.exit(0);
}

Comment by Martin Gerner — March 6, 2009 @ 3:31 am

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .

 
About
The official blog of Romow Computer Web Directory. We blog about the latest computer hardware and software news.

Add to Technorati Favorites

Your email address:




Recent Posts
Archives
Google Crawl Stats
romow.com/computer-blog - SEOmeter SEO tools