JDBC (Java Database Connectivity) is the standard specification for connecting the java application to a Database.
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
CREATE TABLE Student (
id int(10) NOT NULL,
name varchar(45) DEFAULT NULL,
age int(3) DEFAULT NULL,
weight int(3) DEFAULT NULL,
PRIMARY KEY (id)
)
//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
Output
Insert a Record
Output
Records in Table
Also read the below relevant topics.
Also visit Spring JDBCTemplate to check how Spring Framework makes our life easy.