The JDBC(Java Database Connectivity) API(Collection of classes and interfaces) is a technique through which we connect our program to the database smoothly. Java is one of the best languages that provides a connection through to the database smoothly, in comparison to other language.
Figure 1: Description of the working of Jdbc
Steps of Jdbc for connecting the database
We have to import the sql package, which resides in the java .lang package for performing these steps. After this step we have to write our code for connecting to any database.
Syntax:Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); The above line is used for loading any driver class at runtime. We generally do not catch the value (Object of class,Class) returned by this method.
Connection to the Dbms: In the second step we have to create a connection with the database. For this we use the DriverManager class. There is a static method,getConnection("url","user name","password") of DriverManager class.It takes three string type arguments,and returns object of Connection.
Syntax: Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","system","tiger");
Creating and executing a statement: Using a Connection we create statement by the method createStatement() and get the object of Statement.
Syntax:Statement s=con.createStatement();
Processing data returned by Dbms: According to our query we use the data returned by Dbms.
import java.sql.*; class CreateConnection { public static void main(String s[]) { try { //Loading the Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Creating the Connection Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","System","tiger"); if(con!=null) { System.out.println("Connection Successfull"); } else { System.out.println("Connection could not be established"); } //closing the connection conn.close(); } catch(SqlException e) { System.out.println("Exception occured"+ e); } } }
After compilation and execution of above program we get the output as:
Thank You.....
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: