Configuring MySQL on Windows and connect using JDBC

1. Download MySQL Community server for Windows from http://dev.mysql.com/downloads/mysql/

Install and configure MySQL to setup a root and password.

2. Download MySQL GUI Tools for Windows from http://dev.mysql.com/downloads/gui-tools/5.0.html

Create a table under test schema.

3. Download the MySQL JDBC Driver from http://dev.mysql.com/downloads/connector/j/

4. Create a project in Eclipse or any other Java editor. Include the MySQL JDBC Driver tar within the project. Copy the following code to test the connection:

import java.sql.*;

public class main {

/**
 * @param args
 */
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Connection con = null;
	String url = "jdbc:mysql://localhost:3306/";
	String db = "test";
	String driver = "com.mysql.jdbc.Driver";
	String user = "root";
	String pass = "admin";
	try{
	  try{
		  Class.forName(driver).newInstance();
		  con = DriverManager.getConnection(url+db, user, pass);
		  Statement st = con.createStatement();
		  ResultSet res = st.executeQuery("SELECT * FROM  user");
		  while (res.next()) {
			  int id = res.getInt("ID");
			  String fName = res.getString("FNAME");
			  String lName = res.getString("LNAME");
			  String email = res.getString("EMAIL");
			  System.out.println(id + "," 
								+ fName + "," 
								+ lName + "," 
								+ email);
		  }
		  con.close();
	  }
	  catch (SQLException s){
		System.out.println("SQL code does not execute.");
	  }
	}
	catch (Exception e){
	  e.printStackTrace();
	}
}

}//End of class
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s