Nov 2, 2010

Connect to a MySQL database from a Java program

In a program, it may need to store and organise data. To do that in a secure way it must use a database service. MySQL is a good database which can this task by communicating with a Java program. MySQL supports other languages also but for now we only talk about the MySQL-Java combination.

If the Java program need to communicate with the database, the program need to convert instructions into a language which MySQL can understand. To do this Java need a special connector called Jconnector. You need to download and install it.
Link : http://www.mysql.com/downloads/connector/j/

After downloading you may get a  file like "mysql-connector-java-5.1.13.tar.gz"
Unzip this file. Now you can see a file call "mysql-connector-java-5.1.13-bin.jar". You should move this file to the jre/lib/ext, to do that;

$ mv mysql-connector-java-5.1.13-bin.jar   $JAVA_HOME/jre/lib/ext
( "$JAVA_HOME" is where the JDK is installed.)



Now you can try to communicate with the database. You need to create a database in MySQL and if you need create a new user and a password. Then run the MySQL server. After the server is completely up run the Java program. A simple Java program to check the db connection;

/* File name :-  Connect.java



 *
 *
*/

import java.sql.*;

   public class Connect
   {
       public static void main (String[] args)
       {
           Connection conn = null;

           try
           {
               String userName = "root";
               String password = "";
               String url = "jdbc:mysql://localhost/test";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");   }
           catch (Exception e) {
               System.err.println ("Cannot connect to database server"); }
           finally {
               if (conn != null) {
                   try {   conn.close ();
                             System.out.println ("Database connection terminated");}
                   catch (Exception e) { /* ignore close errors */ }
               }
           }
       }
   }

No comments:

Post a Comment

Your comments are always welcome ...