Saturday, March 23, 2013

JDBC connection to the MySQL database with wamp in Eclipse

Java programming with JDBC connection with MySQL from the IDE Eclipse.

Ptograms necessary:
                Eclipse
                Wamp

We are using wamp to install the MySQL required to execute the queries.

Furthermore we require JDBC connector to connect to the MySQL database. Follow the link and download the connector (Connector/J) from the MySQL site: http://dev.mysql.com/downloads/connector/j/

Open eclipse IDE. 
Create a Java Project.
 Insert a class in the default package. 
Right click the project and go to Build Path  → Configure Build Path → Java Build Path → Libraries → Add External JARs →  select the conector.jar file from the location where you saved the file after downloading.

Start the MySQL service from the WampServer.

Write the java program to make connection to the database.



import java.sql.*;

public class mysqltest {
public static void main(String[] args) throws Exception
{
//main class
Class.forName("com.mysql.jdbc.Driver");
//load the jdbc driver class
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/ecommerce","root","");/* red colored part has to be as per your database*/
/*make connection with the database(db name ecommerce, user is root and password is not set in my case put yours in those places with password if you have set password for the database*/
PreparedStatement statement = con.prepareStatement("Select * from products");
/*sql structure to select instances from the table*/
ResultSet result = statement.executeQuery();
/*execution of the database query*/ 
while(result.next()){
System.out.println(result.getString(1) +"\t"+ result.getString(2)+ "\t" + result.getString(3)+ "\t" + result.getString(4));
/*print the result with three attributes from the table 'products in my case' */
}
}
}