JDBC (Java Database Connectivity) is the standard specification for connecting the java application to a Database.

Table of Contents

We need to follow the below steps here.

  • Load and register the JDBC driver.
  • Open a connection to the database.
  • Create a statement object to perform a query.
  • Execute the statement object and return a query resultset.
  • Process the resultset.
  • Close the resultset and statement object.
  • Close the connection.

For our example, we will be connecting to MySQL DB and fetch the records in the Student Table.

Before proceeding with the Java Code, please do the following.

Create Student Table in the Mysql DB

id int(10) NOT NULL,
name varchar(45) DEFAULT NULL,
age int(3) DEFAULT NULL,
weight int(3) DEFAULT NULL,

//Insert the below record in the Student table
INSERT INTO Student (id,name,age,weight) VALUES (1,’Gyan’,15,50);

As we are connecting to MySQL DB, We need to have the mysql-connector-java jar in the classpath.

Java Code

Screen Shot 2020-02-08 at 2.31.15 PM


Screen Shot 2020-02-08 at 2.31.03 PM

Insert a Record

Screen Shot 2020-02-08 at 2.54.27 PM


Screen Shot 2020-02-08 at 2.55.24 PM

Records in Table

Screen Shot 2020-02-08 at 2.52.58 PM

Also read the below relevant topics.

Prepared Statements in JDBC

CallableStatement in JDBC

Also visit Spring JDBCTemplate to check how Spring Framework makes our life easy.

Leave a Reply

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