Complete Java Code for JDBC

MySQL is a popular RDBMS package now-a-days. We would like to establish a database connection with MySQL and to access and manipulate records from MySQL tables. The MySQL version here is 8.0.15 and the name of the database driver (Type 4 driver) is mysql-connector-java-8.0.15.jar. For making JDBC connection we have created a Java program named JdbcTest.java. This program and the JAR file are placed within a directory named JdbcApp under “C:\Users\techguru\Documents”, which is shown below:

       Figure 1: Directory structure of “C:\Users\techguru\Documents\JdbcApp”

 
The following is the list of commands that are executed in the command prompt (cmd) to create database and table and to populate table with records:
mysql> create database test;
mysql> use test;
mysql> create table students (Roll integer(5), Name varchar(20));
mysql> insert into students values(10,'Ramen Das');
mysql> insert into students values(20,'Sampa Pal');
mysql> insert into students values(30,'Kisna Kar');
mysql> select * from students;
+------+-------------+
| Roll | Name        |
+------+-------------+
|  10  | Ramen Das   |
|  20  | Sampa Pal   |
|  30  | Kisna Kar   |
+------+-------------+
 
The complete code is given below:~

JdbcTest.java

import java.sql.*;

public class JdbcTest {

public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
//Step 1: Load the Driver class
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

//Step 2: Establish the Connection
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true";
String username = "root";
String password = "system";
con = DriverManager.getConnection(url, username, password);
if(con!=null)
System.out.println("Successfully connected to " + "MySQL Server 8.0 using TCP/IP...");

//Step 3: Create the Statement
stmt = con.createStatement();

//Step 4: Execute query to get results
rs = stmt.executeQuery("select * from students");
while (rs.next()) {
System.out.println("Roll = " + rs.getInt(1) + "  Name = " + rs.getString(2));
}
}
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
finally {
//Step 5: Close the Connection
try {
if (con != null) {
con.close();
}
}
catch (SQLException e) { }
}
}
}
 
The output of the code from the command prompt is given below:~
C:\Users\techguru> set classpath=C:\Users\techguru\Documents\JdbcApp\mysql-connector-java-8.0.15.jar;

C:\Users\techguru>
cd Documents\JdbcApp

C:\Users\techguru\Documents\JdbcApp>
javac JdbcTest.java

C:\Users\techguru\Documents\JdbcApp>
java JdbcTest
Successfully connected to MySQL server using TCP/IP...
Roll = 10 Name = Ramen Das
Roll = 20  Name = Sampa Pal
Roll = 30  Name = Kisna Kar

In the next section we will learn how to create Servlet and JSP codes using JDBC concept.