Friday, July 27, 2012

How To Establish Java MySql Connection

Connect your java program to MySQL database in 5 simple steps

Accessing a database is one of the basic and essential function that a java program has to perform. So let me help you to connect your java program to a MySQL Database.


Follow these procedures carefully to establish MySQL database connectivity in your java program.


STEP 1
:Download and install MySQL. If you don't have  MySQL installed on your system then download it. 
                                                You can download MySQL from here.


STEP 2: Configure MySQL using "Server Instance Configuration Wizard" (It automatically runs after installation,if not you can start it from MySQL installation folder). It will prompt you to set a password for the database.This password will be required to access the database.


STEP 3: Download JConnector From here. Jconnector is a .jar file which makes the Java-MySQL connection Possible.

STEP 4: Copy the downloaded "mysql-connector-java-5.0.8-bin.jar"(version number may vary)  file from the downloaded package to the location specified below.
          
             Java Installation Folder->jre->lib->ext
        
            Example:  E:\Java7\jdk1.6.0_21\jre\lib\ext

STEP 5: Now is the coding part.We have to include java codes for accessing the database in the program. We have to import java.sql package to the program for that purpose A sample code for establishing Connection is given below.(The code is partial and ephasise only database access)



import java.sql.*;

try
{


/*For Loading Driver*/

Class.forName("com.mysql.jdbc.Driver").newInstance();    

/*For creating a connection with Mysql database*/

Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/Database_name","root","password");



/*For creating a Statement*/

Statement d=c.createStatement();


/*For retrieving result and for executing query*/

ResultSet rst=d.executeQuery("select item from login");
while(rst.next())
{
item=rst.getInt(1);
}



/*closing the statement*/

d.close();


/*closing the connection*/

c.close();


/*For catching and  displaying exceptions if any*/
}catch(Exception e)
{
System.out.println(e.getMessage());
}


You can learn more about JDBC and java sql codes in Oracle Tutorials.

No comments:

Post a Comment