Thursday, February 12, 2015

How to Connect to a MySQL database in java web applications


Follow to the steps to connect the MySQL database


In your project open a new java class and name it, here ill name it as “DatabaseConnection”. Then write these import statements.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;



after importing the above files, inside the DatabaseConnection class write the below code

public Statement stmt;
    public ResultSet res;
    public Connection conn;
   
    public DatabaseConnection(){
       
    }
   
    @SuppressWarnings("CallThreadDumpStack")
    public Connection SetConnection(){
        try{
        
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lms","root","");
            
        }
        catch(Exception e){
           e.printStackTrace();
        }
        return conn;
       
    }
   
    public ResultSet getResult(String query, Connection conn){
            this.conn = conn;
            try{
                stmt = conn.createStatement();
                res = stmt.executeQuery(query);
               
               
            }
            catch(Exception e){
               
            }
            return res;
           
    
        }









After the coding is done see if there are any errors and after finishing everything, run wamp and keep it online.
In the netbeans IDE go to services and and click  databases, there they will show you the MySQL databases, here in my case its “lms”,that’s the database name as shown in the below screenshot.
When you click the particular database the  user is asked to enter the username and the password. When they are filled then we can view the tables in the database.



The full code is provided below

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class DatabaseConnection {
    
    public Statement stmt;
    public ResultSet res;
    public Connection conn;
    
    public DatabaseConnection(){
        
    }
    
    @SuppressWarnings("CallThreadDumpStack")
    public Connection SetConnection(){
        try{
         
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lms","root","");
            
        }
        catch(Exception e){
           e.printStackTrace();
        }
        return conn;
        
    }
    
    public ResultSet getResult(String query, Connection conn){
            this.conn = conn;
            try{
                stmt = conn.createStatement();
                res = stmt.executeQuery(query);
                
                
            }
            catch(Exception e){
                
            }
            return res;
            
     
        }
    }
    



No comments:

Post a Comment