Connecting to database

Connecting to database:
    
    After the Implementation of the JDBC driver, you have to connect the database. Based on the database connection the Driver and the Query may change.

                      
@override the existing program which is previously created, you don't want to create any other new class to connecting the database.


package com.javabasic.jdbc.project;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.lang.ClassNotFoundException;

public class Implementation {

      public static void main(String[] args)
      {
            Connection connection=null;
            Statement statement=null;
           
            try
            {
                  System.out.println("Connecting to Database");
                  Class.forName("com.mysql.jdbc.Driver");
                  connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/my_testing","root","");
                  System.out.println("Connection Successful");
            }
            catch(ClassNotFoundException error)
            {
                 System.out.println("Error:"+error.getMessage());
            }
            catch(SQLException error)
            {
                  System.out.println("Error:" +error.getMessage());
            }
            finally
            {
               if(connection !=null)
                     try {
                           connection.close();
                     }catch(SQLException ignore){}
                     if(statement !=null)
                           try {
                                 statement.close();
                           }catch(SQLException ignore){}
            }
           
                  }
}




         my_testing is the name of the database (optional you can choose your own), root is the user name of the MySQL database and  the next is the password for the user I use the default so, I make is as empty.
         Each and every programs much contain the Exception, this is the good practice for the beginners. Interview point of view the Interviewer may be amaze with your coding. Anyway it will kick out the problem, exception of your code. :)

The Next step: Executing MySQL queries.

No comments:

Post a Comment