How to Create a Database Connection?
Last Updated :
05 May, 2025
Java Database Connectivity is a standard API or we can say an application interface present between the Java programming language and the various databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It basically connects the front end(for interacting with the users) with the backend for storing data entered by the users in the table details. JDBC or Java Database Connection creates a database by following the following steps:
- Import the database
- Load and register drivers
- Create a connection
- Create a statement
- Execute the query
- Process the results
- Close the connection
Step 1: Import the database
Java consists of many packages that ease the need to hardcode every logic. It has an inbuilt package of SQL that is needed for JDBC connection.
Syntax:
import java.sql* ;
Step 2: Load and register drivers
This is done by JVM(Java Virtual Machine) that loads certain driver files into secondary memory that are essential to the working of JDBC.
Syntax:
forName(com.mysql.jdbc.xyz);
class.forname() method is the most common approach to register drivers. It dynamically loads the driver file into the memory.
Example:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e) {
System.out.println("cant load driver class!");
System.Exit(1);
}
Here, the oracle database is used. Now let us considered a random example of hotel database management systems. Now applying SQL commands over it naming this database as ‘sample’. Now suppose the user starts inserting tables inside it be named as “sample1” and “sample2“.
Java
// Connections class
// Importing all SQL classes
import java.sql.*;
public class connection{
// Object of Connection class
// initially assigned NULL
Connection con = null;
public static Connection connectDB()
{
try
{
// Step 2: involve among 7 in Connection
// class i.e Load and register drivers
// 2(a) Loading drivers using forName() method
// Here, the name of the database is mysql
Class.forName("com.mysql.jdbc.Driver");
// 2(b) Registering drivers using DriverManager
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database",
"root", "1234");
// Root is the username, and
// 1234 is the password
// Here, the object of Connection class is return
// which further used in main class
return con;
}
// Here, the exceptions is handle by Catch block
catch (SQLException | ClassNotFoundException e)
{
// Print the exceptions
System.out.println(e);
return null;
}
}
}
Step 3: Create a connection
Creating a connection is accomplished by the getconnection() method of DriverManager class, it contains the database URL, username, and password as a parameter.
Syntax:
public static Connection getConnection(String URL, String Username, String password)
throws SQLException
Example:
String URL = "jdbc:oracle:thin:@amrood:1241:EMP";
String USERNAME = "geekygirl";
String PASSWORD = "geekss"
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Here,
The database URL looks like- jdbc:oracle:thin:@amrood:1221:EMP
The username be-"geekygirl"
The passwords be-"geekss"
Step 4: Create a statement
Query statement is created to interact with the database by following the proper syntax. Before writing the query, we must connect the database using connect() method. For example:
conn = connection.connectDB();
String sql = "select * from customer";
This statement basically shows the contents of the customers' table. We can also create a statement using the createStatement() method of the Connection interface. Here, the object of the statement is mainly responsible to execute queries.
Syntax:
public Statement createStatement()throws SQLException
Example:
Statement s = conn.createStatement();
Step 5: Execute the query
For executing the query (written above), we need to convert the query in JDBC readable format, for that we use the preparedstatement() function and for executing the converted query, we use the executequery() function of the Statement interface. It returns the object of "rs" which is used to find all the table records.
Syntax:
public rs executeQuery(String sql)throws SQLException
Example:
p = conn.prepareStatement(sql);
rs = p.executeQuery();
Step 6: Process the results
Now we check if rs.next() method is not null, then we display the details of that particular customer present in the “customer” table.next() function basically checks if there's any record that satisfies the query, if no record satisfies the condition, then it returns null. Below is the sample code:
while (rs.next())
{
int id = rs.getInt("cusid");
String name = rs.getString("cusname");
String email = rs.getString("email");
System.out.println(id + "\t\t" + name +
"\t\t" + email);
}
Step 7: Close the connection
After all the operations are performed it's necessary to close the JDBC connection after the database session is no longer needed. If not explicitly done, then the java garbage collector does the job for us. However being a good programmer, let us learn how to close the connection of JDBC. So to close the JDBC connection close() method is used, this method close all the JDBC connection.
Syntax:
public void close()throws SQLException
Example:
conn.close();
Sample code is illustrated above:
Java
// Importing SQL libraries to create database
import java.sql.*;
class GFG{
// Step 1: Main driver method
public static void main(String[] args)
{
// Step 2: Creating connection using
// Connection type and inbuilt function
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
con = connection.connectDB();
// Here, try block is used to catch exceptions
try
{
// Here, the SQL command is used to store
// String datatype
String sql = "select * from customer";
p = con.prepareStatement(sql);
rs = p.executeQuery();
// Here, print the ID, name, email
// of the customers
System.out.println("id\t\tname\t\temail");
// Check condition
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println(id + "\t\t" + name +
"\t\t" + email);
}
}
// Catch block is used for exception
catch (SQLException e)
{
// Print exception pop-up on the screen
System.out.println(e);
}
}
}
Output:
Similar Reads
Computer Fundamentals Tutorial This Computer Fundamentals Tutorial covers everything from basic to advanced concepts, including computer hardware, software, operating systems, peripherals, etc. Why Learn Computer FundamentalsYour computer can solve complex problem in milliseconds!Helps you understand how computers work and solve
4 min read
Fundamental
Computer HardwareComputer hardware refers to the physical components of a computer that you can see and touch. These components work together to process input and deliver output based on user instructions. In this article, weâll explore the different types of computer hardware, their functions, and how they interact
10 min read
What is a Computer Software?Computer Software serves as the backbone of all digital devices and systems. It is an integral part of modern technology. Unlike hardware which comprises physical components, software is intangible and exists as a code written in programming language. This article focuses on discussing computer soft
8 min read
Central Processing Unit (CPU)The Central Processing Unit (CPU) is like the brain of a computer. Itâs the part that does most of the thinking, calculating, and decision-making to make your computer work. Whether youâre playing a game, typing a school assignment, or watching a video, the CPU is busy handling all the instructions
6 min read
Input DevicesInput devices are important parts of a computer that help us communicate with the system. These devices let us send data or commands to the computer, allowing it to process information and perform tasks. Whether it's typing on a keyboard or clicking a mouse, these devices enable us to interact with
11 min read
Output DevicesOutput devices are hardware that display or produce the results of a computer's processing. They convert digital data into formats we can see, hear, or touch. The output device may produce audio, video, printed paper or any other form of output. Output devices convert the computer data to human unde
9 min read
Memory
Computer MemoryMemory is the electronic storage space where a computer keeps the instructions and data it needs to access quickly. It's the place where information is stored for immediate use. Memory is an important component of a computer, as without it, the system wouldnât operate correctly. The computerâs opera
9 min read
What is a Storage Device? Definition, Types, ExamplesThe storage unit is a part of the computer system which is employed to store the information and instructions to be processed. A storage device is an integral part of the computer hardware which stores information/data to process the result of any computational work. Without a storage device, a comp
11 min read
Primary MemoryPrimary storage or memory is also known as the main memory, which is the part of the computer that stores current data, programs, and instructions. Primary storage is stored in the motherboard which results in the data from and to primary storage can be read and written at a very good pace.Need of P
4 min read
Secondary MemorySecondary memory, also known as secondary storage, refers to the storage devices and systems used to store data persistently, even when the computer is powered off. Unlike primary memory (RAM), which is fast and temporary, secondary memory is slower but offers much larger storage capacities. Some Ex
7 min read
Hard Disk Drive (HDD) Secondary MemoryPrimary memory, like RAM, is limited and volatile, losing data when power is off. Secondary memory solves this by providing large, permanent storage for data and programs.A hard disk drive (HDD) is a fixed storage device inside a computer that is used for long-term data storage. Unlike RAM, HDDs ret
11 min read
Application Software
MS Word Tutorial - Learn How to Use Microsoft Word (2025 Updated)Microsoft Word remains one of the most powerful word processing program in the world. First released in 1983, this word processing software has grown to serve approximately 750 million people every month. Also, MS Word occupies 4.1% of the market share for productivity software.With features like re
9 min read
MS Excel Tutorial - Learn Excel Online FreeExcel, one of the powerful spreadsheet programs for managing large datasets, performing calculations, and creating visualizations for data analysis. Developed and introduced by Microsoft in 1985, Excel is mostly used in analysis, data entry, accounting, and many more data-driven tasks.Now, if you ar
11 min read
What is a Web Browser and How does it Work?The web browser is an application software used to explore the World Wide Web (WWW). It acts as a platform that allows users to access information from the Internet by serving as an interface between the client (user) and the server. The browser sends requests to servers for web documents and servic
4 min read
Excel SpreadsheetAn Excel spreadsheet, called a workbook, contains one or more worksheets, each a grid of 1,048,576 rows and 16,384 columns for data management. Workbooks organize related data across multiple worksheets in a single file.1. Understanding Excel Workbooks and WorksheetsWorkbook: A single Excel file con
4 min read
System Software
Programming Languages
C Programming Language TutorialC is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
4 min read
Python Tutorial - Learn Python Programming LanguagePython is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
7 min read
Java TutorialJava is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
7 min read
JavaScript TutorialJavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
8 min read