Skip to main content

JDBC connectivity Explanation: The interface or channel between Front end(Java) and Back-end (database)


Establishing JDBC Connection in Java
Before establishing a connection between front end i.e your Java Program and back end i.e the database we should learn what precisely a JDBC is and why it came to existence.
What is JDBC ?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is an standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.
Why JDBC came into existence ?
As previously told JDBC is an advancement for ODBC, ODBC being platform dependent had a lot of drawbacks. ODBC API was written in C,C++, Python, Core Java and as we know above languages (except Java and some part of Python )are platform dependent . Therefore to remove dependence, JDBC was developed by database vendor which consisted of classes and interfaces written in Java.

Steps for connectivity between Java program and database
1. Loading the Driver
To begin with, you first need load the driver or register it before using it in the program . Registration is to be done once in your program. You can register a driver in one of two ways mentioned below :
  • Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object .The following example uses Class.forName() to load the Oracle driver –
 Class.forName(“oracle.jdbc.driver.OracleDriver”);
  •  DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time . The following example uses DriverManager.registerDriver()to register the Oracle driver –
 DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
2. Create the connections
After loading the driver, establish connections using :
 Connection con = DriverManager.getConnection(url,user,password)
user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator. It can be created as follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used , @localhost is the IP Address where database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by programmer before calling the function. Use of this can be referred from final code.
3. Create a statement
Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Here, con is a reference to Connection interface used in previous step .
4. Execute the query
Now comes the most important part i.e executing the query. Query here is an SQL Query . Now we know we can have multiple types of queries. Some of them are as follows:
  • Query for updating / inserting table in a database.
  • Query for retrieving data .
The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.
The executeUpdate(sql query) method ofStatement interface is used to execute queries of updating/inserting .
Example:
int m = st.executeUpdate(sql);
if (m==1)
    System.out.println("inserted successfully : "+sql);
else
    System.out.println("insertion failed");
Here sql is sql query of the type String
5.Close the connections
So finally we have sent the data to the specified location and now we are at the verge of completion of our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
Example :
 con.close();
Implementation
importjava.sql.*;
importjava.util.*;
class Main
{
    public static void main(String a[])
    {
        //Creating the connection
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "system";
        String pass = "12345";

        //Entering the data
        Scanner k = new Scanner(System.in);
        System.out.println("enter name");
        String name = k.next();
        System.out.println("enter roll no");
        int roll = k.nextInt();
        System.out.println("enter class");
        String cls =  k.next();

        //Inserting data using SQL query
        String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
        Connection con=null;
        try
        {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

            //Reference to connection interface
            con = DriverManager.getConnection(url,user,pass);

            Statement st = con.createStatement();
            int m = st.executeUpdate(sql);
            if (m == 1)
                System.out.println("inserted successfully : "+sql);
            else
                System.out.println("insertion failed");
            con.close();
        }
        catch(Exception ex)
        {
            System.err.println(ex);
        }
    }
}


Comments

Popular posts from this blog

What is QinQ(IEEE 802.1ad)

What is QinQ In this section, we will see about Switching concept QinQ. In service provider networks, This is very important. Service provider use this Switching function to pass customer data from one end to other end with two vlan id’s in own switching network.  Explanation: The QinQ technology is called VLAN dot1q tunnel, 802.1Q tunnel, VLAN Stacking technology. The standard comes from IEEE 802.1ad and it is the expansion of the 802.1Q protocol. QinQ adds one layer of 802.1Q tag (VLAN tag) based on the original 802.1Q packet head. With the double layers of tags, the VLAN quantity is increased to 802.1Q. QinQ encapsulates the private network VLAN tag of the user in the public(service provider) network VLAN Tag to make the packet with double layers of VLAN Tags cross the backbone network (public network) of the operator. In the public network, the packet is passed according to the out layer of VLAN tag (that is the public network VLAN Tag) and the private network

Beacon Frames, Probe request and response

Beacon frame  is one of the management frames in  IEEE 802.11  based WLANs. It contains all the information about the network. Beacon frames are transmitted periodically, they serve to announce the presence of a wireless LAN and to synchronise the members of the service set. Beacon frames are transmitted by the  access point  (AP) in an infrastructure  basic service set  (BSS). In IBSS network beacon generation is distributed among the stations. Beacons are sent periodically at a time called Target Beacon Transmission Time(TBTT) 1 TU = 1024 microseconds Beacon interval =100 TU (100x 1024 microseconds or 102.4 milliseconds) 1. Timestamp (8 byte) 2. Beacon Interval (2 byte) 3. Capability info (2 byte) 4. SSID (variable size) 5. Supported Rates (variable size) Probe Request:  A station or client becomes active or on a PC when the wlan card it enabled it becomes active sends a probe request frame when it needs to obtain information from another station or access point.

Difference between Polling and Trap in Network Management – Which one is better?

A Network Manager’s job is to get data from Network Elements and present it to the administrators or operators. There are two ways of doing this activity:  1) Polling and 2) Trap . Here is a quick difference between the two: Polling  : A traditional way of providing operators with the network elements information. It’s characteristics are as follows: ·        Pull Mechanism – Requests and get information from network elements at periodic intervals. The periodic interval is most often configurable. ·        Provides non-real time information. It may happen that some changes happen in network element but polling happens an hour after that. Thus, operator gets to know about the changes after an hour. ·        Higher bandwidth needed. Traps  : When an alarm situation exists a trap can be generated, or if some changes happen at network element, an attribute value change event can be generated by the agent. It’s characteristic are as follows: ·        Push Mechanism – E