How To Connect To A Database in Java? – JDBC Tutorial

Last updated on Jul 26,2023 33.6K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

How To Connect To A Database in Java? – JDBC Tutorial

edureka.co

Java, being one of the most prominent programming languages, provides extensive support to databases. It helps us to connect to various databases through JDBC (Java Database Connectivity). In this article, I will tell you how to connect to a database and execute queries using JDBC.

Below topics are covered in this article:

Introduction to JDBC

JDBC is one of the standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. This API lets you encode the access request statements, in Structured Query Language (SQL).  This mainly involves opening a connection, creating a SQL Database, executing SQL queries and then arriving at the output.

JDBC API can be used to access tabular data stored in any relational database. With this, you can update, save, fetch and delete the data from the databases. It is similar to the Open Database Connectivity (ODBC) provided by Microsoft.

For a better understanding of working of JDBC, let’s dive deeper into the topic and understand the architecture that lies behind Java Database Connectivity.

Common JDBC Components

The JDBC API provides the following interfaces and classes −

Now let’s move on to the next topic and look at the steps required to create a JDBC Application.

Steps to create JDBC Application

In order to create a JDBC Application, you need to follow a few steps. Let’s see what are they.

  1. Import the packages: You need to include all the packages that contain the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.

  2. Register the JDBC driver: Here you have to initialize a driver so that you can open a communication channel with the database.

  3. Open a connection: Here, you can use the getConnection() method to create a Connection object, which represents a physical connection with the database.

  4. Execute a query: This actually requires to use an object of type Statement for building and submitting an SQL statement to the database.

  5. Extract data from the result set: It is suggested that you use the appropriate getXXX() method to retrieve the data from the result set.

  6. Clean up the environment: Here, it is essential to explicitly close all database resources versus relying on the JVM’s garbage collection.

Now as you have seen various steps involved to create a JDBC Application, let’s see an example code to create a database and establish a connection.

package Edureka;
import java.sql.*;
import java.sql.DriverManager;
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,"root","");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close()
}catch(SQLException se2){
}// nothing can be done
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
} // end Example

Above code creates a table in your localhost database. To insert the values in the created database, you can refer to the below code. I will be writing the code only for step 4. Rest of the code remains the same as above.

//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE EMPLOYEES " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
System.out.println("Inserting records into the table...");
stmt =conn.createStatement();
String sql ="INSERT INTO Employees VALUES (100, 'Kriss', 'Kurian', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Employees VALUES (101, 'Enrique', 'John', 25)";
stmt.executeUpdate(sql);
sql= "INSERT INTO Employees (102, 'Taylor', 'Swift', 30)";
stmt.executeUpdate(sql);
sql= "INSERT INTO Employees VALUES(103, 'Linkin', 'Park', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");

So this is how you can establish a connection to the database and insert values in the tables. Now let’s move further and understand various JDBC Driver Types

JDBC Driver Types

JDBC drivers are used to implement the defined interfaces in the JDBC API, for interacting with the database server. Essentially, a JDBC driver does three things and they are as follows:
1. Establishes a connection with a data source.
2. It will send queries and update statements to the data source.
3. Finally, it processes the results.

For example, JDBC drivers help you to open a database connection to interact with it by sending SQL or database commands. If you wish to know more about types of JDBC Driver, you can refer to this article on JDBC Drivers.

Now let’s move further and understand JDBC Connections.

JDBC Connections

You can create a connection using the database URL, username, and password and also using properties object.

Finally, to end the database session, you need to close all the database connections. However, if you forget, Java’s garbage collector will close the connection when it cleans up stale objects.

conn.close(); // Used to close the connection

That was all about Java Database Connectivity. If you wish to know more about JDBC, you can refer to this article on Advanced Java Tutorial. This brings us to the end of the article on ‘how to connect to a database’. I hope I have thrown some light on to your knowledge on JDBC.

Check out the Java Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.

Got a question for us? Please mention it in the comments section of this “how to connect to a database” article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 11th May,2024

11th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 1st June,2024

1st June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial