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:


Leave a comment »

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <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
Blogging Categories
Archives
Romow Computer Directory
Blogroll
Google Crawl Stats
romow.com/computer-blog - SEOmeter SEO tools