Using MySql with Eclipse IDE -


Here we are using Eclipse Luna, The step by step process of using Eclipse with MySql is as follows -

1- Open the Eclipse Luna, Go to File -> New -> Project.

2- It opens a New Project Wizard window, From Wizards, select java -> Java Project and click Next.

3- Enter the desired project name in Project Name Textbox; here we used "MY_JDBC_DEMO" and leave other options as it is. And click on Finish.

4- Right click on src folder of Project, select New -> Package. And create a desired package name. Here we used my_jdbc_demo.

5- Right click on package name, select New -> Class. Create a desired class name. Here we used MY_JDBC_DEMO.

6- TO connect Java Applications with MySql RDBMS you need to download MySql Connector jar file -
    download mysql connector jar file
7- To load the jar file in your project Right Click on Project and select option "Properties". As shown in below figure -

8- Click on "Add External JARs" and add mysql connector jar file from your system.
9- And now we can write our code for JDBC applications.

Example 1 -

Use of Statement interface with executeQuery() method - In this example we select and print the data of a "Employee" table exists in database "Company".
package my_jdbc_demo;

import java.sql.*;
public class MY_JDBC_DEMO {

    public static void main(String[] args) {
        
        Connection con;
        try
        {
            // Load the driver
            Class.forName("com.mysql.jdbc.Driver");
            
            // Establish connection
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Company", "root", "root");
            
            // Create Statement Object
            Statement st = con.createStatement();
            
            // Execute query
            ResultSet rs = st.executeQuery("select * from Employee");
            while(rs.next())
            {
                System.out.println(rs.getInt(1)+"   "+rs.getString(2)+"   "+rs.getInt(3));
            }
            
            // Close the connection
            con.close();
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
      
    }
}    

Output -

1   Rohit   1000000
2   Mohit   2000000    

Example 2 -

Use of Statement Interface with executeUpdate() method - In this example we insert a new row of data in "Employee" table exists in database "Company".
package my_jdbc_demo;

import java.sql.*;
public class MY_JDBC_DEMO {

    public static void main(String[] args) {
        
        Connection con;
        try
        {
            // Load the driver
            Class.forName("com.mysql.jdbc.Driver");
            
            // Establish connection
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Company", "root", "root");
            
            // Create Statement Object
            Statement st = con.createStatement();
            
            // Execute query
            int row_affected = st.executeUpdate("insert into Employee values(3, 'Ajay', 1500000)");
            System.out.println("Number of Rows affected by query = "+row_affected);
            
            // Close the connection
            con.close();
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
      
    }
        

Output -

Number of Rows affected by query = 1
As the output is one that means our query is successfully executes. We can also see the result by executing the following query in MySql Command window -
mysql> select * from Employee;
It produce the following output now -

1       Rohit       1000000
2       Mohit     2000000
3       Ajay        1500000
    
        

Example 3-

Use of PreparedStatement with executeQuery() method - In this example we select and print the data from a "Employee" table exists in database "Company". The data will be selected according to user input at run time.
package my_jdbc_demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
public class MY_JDBC_DEMO {

    public static void main(String[] args) {
        
        Connection con;
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter first employee id");
            int id1 = Integer.parseInt(br.readLine());
            System.out.println("Enter second employee id");
            int id2 = Integer.parseInt(br.readLine());
            
            // Load the driver
            Class.forName("com.mysql.jdbc.Driver");
            
            // Establish connection
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Company", "root", "root");
            
            // Create Statement Object
            PreparedStatement ps = con.prepareStatement("select * from Employee where eid = ? or eid = ?");
            
            
            ps.setInt(1, id1); // set the value of first parameter (ist ?).
            ps.setInt(2, id2);  // set the value of second parameter (2nd ?).
            
            // Execute query
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            
            // Get total number of columns
            int cols = rsmd.getColumnCount();
            
            // To print columns names of table
            for(int i =1; i<=cols; i++)
            {
                System.out.print(rsmd.getColumnName(i)+"   ");
            }
            
            // for next line
            System.out.println();
            
            // to print values contained in table
            while(rs.next())
            {
                System.out.println(rs.getInt(1)+"   "+rs.getString(2)+"   "+rs.getInt(3));
            }
            
            // Close the connection
            con.close();
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
      
    }

}
        

Output -

Enter first employee id
1
Enter second employee id
3

eid   ename   salary   
1     Rohit   800000
3     Ajay    1500000