JDBC Program in Java

Amansingh Javatpoint
2 min readApr 16, 2021

--

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 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.

--

--

No responses yet