In 5 Simple Steps – Establish JDBC Connection in Java

Free Java courses with 37 real-time projects - Learn Java

1. Objective

In our last tutorial, we discussed Socket Programming in Java. Here, we are going to learn about what is JDBC Connection in Java. Moreover, we will discuss important detail related to Java Database Connectivity. At last, we will see various JDBC connection steps involved in the creation of the connection and many other things.

So, let us start JDBC Connection in Java.

In 5 Simple Steps - Establish JDBC Connection in Java

In 5 Simple Steps – Establish JDBC Connection in Java

2. JDBC Connection in Java

JDBC is an acronym for Java Database Connectivity. It’s a headway for ODBC (Open Database Connectivity). JDBC Connection in Java is a standard API particular created with a specific end goal to move information from frontend to backend. This Java API comprises of classes and interfaces written in Java. It fundamentally goes about as an interface (not the one we use in Java) or channel between your Java program and databases i.e. JDBC connection in Java, sets up a connection between the two with the goal that a developer could send information from Java code and store it in the database for some time later.

Do you know What is Java Character Class Methods

Why JDBC Connection in Java came into existence?

As beforehand told JDBC is a headway for ODBC, ODBC being stage subordinate had a ton of downsides. ODBC API was composed in C, C++, Python, and Core Java and as we probably are aware above dialects (aside from Java and some piece of Python) are stage subordinate. Accordingly, to expel reliance, JDBC connection in Java was created by database merchant which comprised of classes and interfaces written in Java.

3. How to Connect Java Program and Database

Here, are the following steps for JDBC Connection in Java between Java program & Database

Let’s Explore Types of Inner Classes in Java

Establish JDBC Connection in Java

Establish JDBC Connection Between Java Program and Database

a. Stacking the Driver

Stacking the driver is the first step of JDBC Connection in Java. In any case, you first need stack the driver or enlist it before utilizing it in the program. Enlistment is to be done once in your program. You can enroll a driver in one of two courses specified beneath:

  • forName(): Here we stack the driver’s class record into memory at the runtime. No need of utilizing new or formation of question. The accompanying illustration utilizes Class.forName() to stack the Oracle driver –

Class.forName(“oracle.jdbc.driver.OracleDriver”);

  • registerDriver(): DriverManager is a Java inbuilt class with a static part enlist. Here we call the constructor of the driver class at an incorporate time. The accompanying illustration utilizes DriverManager.registerDriver()to enlist the Oracle driver –

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

Read about Java String, Methods, And Constructor – Syntax and Example

b. Create the Connections

Subsequent to stacking the driver, build up associations utilizing:
Connection con = DriverManager.getConnection(url,user,password)

  • user – username from which your sql summon provoke can get to.
  • password – watchword from which your sql summon provoke can get to.
  • con- is a reference to Connection interface.
  • url- Uniform Resource Locator. It can be made as takes after:

String url = ” jdbc:oracle:thin:@localhost:1521:xe”

Where Oracle database utilize, thin is the driver utilized, @localhost is the IP Address where a database is put away, 1521 is the port number and xe is the specialist organization. Every one of the 3 parameters above is of String write and are to be announced by software engineer before calling the capacity. Utilization of this can allude from conclusive code.

c. Make an Announcement

Once an association is built up you can collaborate with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces characterize the strategies that empower you to send SQL summons and get information from your database.

Do you Difference Between Abstract Class and Interface in Java

Utilization of JDBC Statement is as per the following:

Statement st = con.createStatement();

Here, coa n is a reference to Connection interface utilized as a part of past advance.

d. Execute the Question

Presently comes the most imperative part i.e executing the question. A question here is a SQL Query. Presently we know we can have numerous sorts of questions. Some of them are as per the following:

  • Query for refreshing/embeddings table in a database.
  • Query for recovering information.

The executeQuery() technique for Statement interface utilizes to execute questions of recovering esteems from the database. This strategy restores the protest of ResultSet that can utilize to get every one of the records of a table.

The executeUpdate(sql inquiry) technique of Statement interface utilize to execute inquiries of refreshing/embeddings.

Let’s revise Java Garbage Collection Algorithm – Mark and Sweep Algorithm

Example:-

int m = st.executeUpdate(sql);
in the event that (m==1)
System.out.println("inserted effectively : "+sql);
else
System.out.println("insertion fizzled");

Here SQL will be SQL inquiry of the sort String

e. Close the Associations

So at long last, we have sent the information to the predetermined area and now we are at the skirt of a fulfillment of our undertaking.
By shutting association, objects of Statement and ResultSet will shut naturally. The nearby() technique for Connection interface is utilize to close the association.

Example –

con.close();

Implementation –

importjava.sql.*;
importjava.util.*;
class Main
{
    public static void main(String a[])
    {
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "system";
        String pass = "12345";
        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();
        String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
        Connection con=null;
        try
        {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            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);
        }
    }
}
This was all about JDBC Connection in Java Tutorial. Hope you like our explanation.

4. Conclusion

Hence, in this Java tutorial, we learned what is JDBC Connection in Java and how to establish JDBC connection in Java between Java program and Database with an example program. Furthermore, if you have any query feel free to ask in the comment section.

Related Topic- The Island of Isolation in Java with Example

For reference 

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *