Connect MySQL and Apache NetBeans

Before you start connecting Appache and MySQL make sure that MySQL Database is up and running. You can setup a mySQL Server in your localhost using XAMPP Server.

Let’s simply connect the MySQL Database and Appache Netbeans IDE with the help of Library jar file and a piece of code. So let’s see how we can do it.


Add Library File

Download “mysql connector java” jar file and Add the same to Library folder in Appache Netbeans.

Java Code to Establish MySQL Connectivity

Copy and Paste below code and change connection string to match your database to connect MySQL Database into Apache NetBeans. Replace your connection string by your database port number ed code to your project. Change your connection string by replacing your database port number (Will be 3306 by default if you are not changed), database name, username and password to connect your database.

What I recommend is to create a database connection class and call it whenever you required a database connection across your project.


    public class DBConnect{
    public static Connection connect(){
         Connection con =null;
        try {
           
            Class.forName("com.mysql.jdbc.Driver");
            con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","");
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    return con;
    }
    
    }
  



Calling DBConnect Class

We can call the DBConnect Class whenever we required. it can be either loading a jFrame or Button Click. Below example showing the ‘DBConnect’ will be called while user clicking the Submit button.




  private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                              
         try {
             // TODO add your handling code here:
             
             con1 = DBConnect.connect();
             Statement stmt = con1.createStatement();
             if(con1==null)
                 JOptionPane.showMessageDialog(this,"Unable to Connect DB");
            
// Your Code here
         } catch (SQLException ex) {
             Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
         }
        
    } 
  
Hope this little article will help you to connect MySQL Database and Apache NetBeans. Thank you






Post a Comment

Previous Post Next Post