×

JDBC Program in Java

JDBC Program in Java

JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java Database Connectivity. It is used to connect a Java program to the database. Thus, using JDBC, we can retrieve, update, and delete data from the database. The JDBC program in Java shows how to connect to a database and execute DML (Data Manipulation Language) and DDL (Data Definition Language) statements regarding the database.

Connecting to a Database

There are 5 steps that are involved in the connection to a database.

1) Register Driver: The forName() method of the Class class is used for driver registration. For example, to register the driver of MySQL database, the following statement is used.

Class.forName("com.mysql.jdbc.Driver"); 

2) Create connection: After driver registration, a connection to the database is required. To achieve the same, the getConnection() method is used.

 Connection connection = DriverManager.getConnection(
jdbc:mysql://localhost:3306/database_name, userName, password);  

3) Create Statement: The third step is to create a statement object. The statement object is responsible for the query execution. The following statement creates a statement object.

Statement sttmnt = connection.createStatement(); 

4) Execute Queries: The penultimate step is to execute the query using the statement object created in the previous step. The executeQuery() method does the execution. This method takes the query statement in its parameter.

ResultSet resSet = sttmnt.executeQuery(Query statement); 

Query statement is of type string.

5) Close Connection: After completing the database related task it is required to close the database connection, which is done by invoking the close() method. The following statements shows how the connection can be closed.

 resSet.close();
sttmnt.close();
connection.close(); 

Before writing the code, it is important to know an essential prerequisite for connecting to a database.

To connect to a database, its concerned connector jar file is required. In the following code, the connection is getting established to a MySQL database. Therefore, it is required to have a connector jar file for MySQL. While executing the following code, use the command written below.

Java -cp .;mysqlconnector.jar MySqlConnExample

In the classpath, it is mandatory to give the location of the connector jar file; otherwise, exceptions are raised.

The following program uses the steps, defined above, to connect to MySQL and then demonstrates the execution of queries.

FileName: MySqlConnExample.java

 // Importing the sql package
import java.sql.*;
// Importing the sql package
import java.sql.*;
public class MySqlConnExample
{
// URL for the database
// 3306 is the TCP port number
// Database name is first
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/first";
// driver class
static final String DRIVER = "com.mysql.jdbc.Driver";
// User name and password for accessing the database
static String usrName = "root";
static String pswd = "root";
// driver method
public static void main(String argvs[])
{
Connection connection = null; // for connection
String qry = null; // for storing queries
Statement sttmnt = null; // for query execution
ResultSet resSet = null; // for storing the result of query
try
{
// Registering the DRIVER
Class.forName(DRIVER); 
System.out.println("Connecting to the database");
// Creating a connection to the database
connection = DriverManager.getConnection(DATABASE_URL, usrName, pswd); 
// the query to be executed
// orderId, customerId, city are the fields/ column names
// orders is the name of a table present in the database first
qry = "select orderId, customerId, city from orders";
// for query execution
sttmnt = connection.createStatement(); 
// excuting the query and storing the result
resSet = sttmnt.executeQuery(qry); 
while(resSet.next() ) 
{
// Fetching the results using the column name
int oId  = resSet.getInt("orderId");
int cId = resSet.getInt("customerId");
String city = resSet.getString("city");
//printing the values
System.out.print("Order ID: " + oId);
System.out.print(", Customer ID: " + cId);
System.out.println(", City: " + city);
}
}
catch(SQLException sqlExpn)
{
               // For catering the errors generated from JDBC
               sqlExpn.printStackTrace();
}
catch(Exception expn)
{
               // For catering the errors generated from Class.forName
               expn.printStackTrace();
}
finally
{
               try
               {
                              // doing the cleaning up work
                              // closing the connection
                              resSet.close();
                              sttmnt.close();
                              connection.close();
                               System.out.println("Connection Closed");
               }
               catch(SQLException sqlExpn)
               {
                               sqlExpn.printStackTrace();
               }
}
}
} 

Output:

 Connecting to the database
Order ID: 9321, Customer ID: 10, City: Gorakhpur
Order ID: 10202, Customer ID: 5, City: Noida
Order ID: 10292, Customer ID: 5, City: Delhi
Order ID: 18292, Customer ID: 2, City: Patna
Order ID: 78421, Customer ID: 3, City: Pune
Order ID: 80370, Customer ID: 9, City: Raipur
Order ID: 84170, Customer ID: 6, City: Nagpur
Order ID: 86770, Customer ID: 8, City: Hapur
Connection Closed 

Explanation: First, we are establishing the connection with the database using the appropriate credentials. Then we are fetching the result from the table Orders of the database. Notice, the closing of the connection is done in the finally block. Because no matter what happens eventually, the established connection has to be terminated eventually, and execution of the finally block is not dependent on the generation of exceptions.

Note: Not only MySQL, we can also establish a connection to other databases like Oracle, Postgres, etc. To achieve that, the driver class for the databases is required. Also, the connector jar file of the concerned database must be known to the classpath of the program.


Related Topics

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.