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.

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

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.

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.

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.

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.

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

Output:

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.

Pin It on Pinterest

Share This