Java / Java Database Connectivity (JDBC)
Introduction to JDBC and Database Connections
In this tutorial, you will get introduced to JDBC, understand its architecture and learn how to establish database connections using JDBC. You will learn about the role of JDBC dr…
Section overview
5 resourcesCovers database interaction with JDBC API for connecting, querying, and updating databases.
Introduction
This tutorial aims to introduce you to the Java Database Connectivity (JDBC), which is a specification providing a complete set of interfaces that allows for portable access to an underlying database. JDBC plays a crucial role in handling database connections within the Java programming language.
By the end of this tutorial, you should understand the JDBC architecture, how to establish a database connection using JDBC, and the role of JDBC drivers in facilitating connections between Java applications and various databases.
Prerequisites
To follow along with this tutorial, you should:
- Have a basic understanding of the Java programming language
- Have a basic understanding of SQL and Databases
- Have a Java Development Kit (JDK) installed on your machine
- Have a SQL database available for connection
Step-by-Step Guide
JDBC provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers:
- JDBC API: This provides the application-to-JDBC Manager connection.
- JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source.
Establishing a Database Connection
To connect to a database, you need a JDBC driver. This driver communicates with the database server and allows you to execute SQL statements.
Here's how to establish a connection:
// Importing required packages
import java.sql.*;
public class Main {
public static void main(String[] args) {
// Database URL
String url = "jdbc:dbms://localhost:port/database_name";
try {
// Load and register driver
Class.forName("com.example.jdbc.Driver");
// Establish connection
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection established successfully.");
// Close connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the above example, replace "dbms", "localhost", "port", "database_name", "username", "password", and "com.example.jdbc.Driver" with your actual database details and JDBC driver.
Code Examples
Querying Data from a Database
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/demo_db";
String user = "root";
String password = "password";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// Execute a query
String sql = "SELECT id, name, age FROM Users";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, a SQL SELECT query is executed to fetch data from the 'Users' table. ResultSet 'rs' is used to get the data.
Summary
In this tutorial, you've learned about JDBC, its architecture, and how to establish a database connection using JDBC. You've also seen how to query data from a database.
To continue your learning, you might want to explore how to execute other types of SQL statements like UPDATE, DELETE, and INSERT. You can also learn about PreparedStatement and CallableStatement in JDBC.
Practice Exercises
-
Write a JDBC program to connect to your database and execute a simple SQL SELECT statement to fetch data from a table.
-
Write a JDBC program to insert a new record into a table in your database.
-
Write a JDBC program to update a record in a table in your database.
References
- Official Java Documentation: JDBC Basics
- JDBC API Documentation
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article