Wednesday, 28 September 2011

Database Connectivity


Connecting a Database usually involves 2 important steps which are
  •      Establishing a connection.
  •      Connecting with the URL.

Establishing a connection:
      Inorder to establish a connection, we must load the driver that is going to act as an interface between your java code and the database. For this, we can use Class.forName() method that is defined in Class. This method will return the object of the interface by loading  the specifed driver which can be JDBC or ODBC or Sun depending on the Database going to be used. If for example, jdbc driver is specified, it will load the jdbc driver as the interface between your code and the database. 

Connecting with the URL:
     The Connection object must be created before connecting to the URL. This can be done as follows : 
     Connection con=DriverManager.getConnection(url,username,password); 
      DriverManager class provides a static method, getConnection() for connecting the host system with the database server. Here "url" is the path of the db server and "username" and "password" are the host system's username and password respectively. The "url" part consists of type of the driver followed by ip address or name of the system which inturn followed by port id. For mysql the default port is 3306. 

Example program for Database connectivity: 

import java.sql.*;
public class DBConnect
{
    public static void main(String args[]) throws SQLException, ClassNotFoundException
    {
        Connection con=null;

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql:// 172.220.26.5 : 3306/","guest","guest");
           
        }
        catch(SQLException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            if(con!=null)
                con.close();

        }
    }
}
     And its a good practice to close the connection in the finally block, inorder to release the memory that was allocated for the database.     
     

No comments:

Post a Comment