Using MySql with NetBeans IDE -


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


1- Open The NetBeans IDE, Go to file and select NewProject option, It will open a windows as shown below -

2- In the Categories selct first option "Java" and in Projects list selct "Java Application"" and click on Next.
3- In the next window change the project name you desired, here we are using name ? MY_JDBC_DEMO. And leave everything else to default and click on Finish.

4- It will create a project structure as shown in the below figure -

Note - It creates a package and main class with the same name as Project name.
5- TO connect Java Applications with MySql RDBMS you need to download MySql Connector jar file -
    download mysql connector jar file
6- To load the jar file in your project Right Click on Libraries and select option Add JAR/Folder. As shown in below figure -

7- A new window will be opened, browse and load the downloaded MySql connector "mysql-connector.jar".

8- 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 all the data of a "Employee" table exists in "Company" database.
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");

           // 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 -


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