Pages

This blog is under construction

Monday, November 26, 2018

How to connect JAVA application with mysql database

Example:

package javaapplication36;
import java.sql.*;

public class JavaApplication36 {

public static void main(String[] args) {
        try{
                  //Class.forName("com.mysql.jdbc.Driver");
                   // comment above line if jar file is uploaded manually in your project  
                 Connection con =    DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","mysql@123");
                
   //here test is database name, 3306 is default port, root is username and mysql@123 is password
                Statement stmt=con.createStatement();
                ResultSet rs=stmt.executeQuery("select * from tab1"); 
 // tab1 is a table in test database 
                while(rs.next())
                 System.out.println(rs.getInt(1)+"  "+rs.getString(2)); 
                con.close(); 
                     
             }
   
        catch(Exception e)
          { System.out.println(e);
         } 
    }
}

To connect java application with the mysql database, mysqlconnector.jar file is required to be loaded.

Step 2: download JDBC Driver for MySQL (Connector/J)
Step 3: select operating system: Platform Independent and click on the download
Step 4: click on  No thanks, just start my download at the bottom
Step 5: Extract downloaded file
Step 6: open your NetBeans project  //Manually upload jar file in the project
Step 7: Right-click on libraries folder of your project
Step 8: click on add Jar/Folder…
Step 9: select jar file mysql-connector-java-8.0.13 from downloaded folder
Step 10: now compile your program


No comments:

Post a Comment