How to Connect JDBC to SQL (Step-by-Step Guide)
Connecting Java applications to a SQL database is a very common requirement in backend development. JDBC (Java Database Connectivity) is the standard Java API that allows Java programs to interact...
Jagnyadatta Dalai is a content creator on QueueVerse, sharing insights and expertise on various topics. With 0 published articles, they contribute valuable knowledge to the community.
Advertisement
Connecting Java applications to a SQL database is a very common requirement in backend development. JDBC (Java Database Connectivity) is the standard Java API that allows Java programs to interact with databases such as MySQL, PostgreSQL, Oracle, SQL Server, etc. In this blog, you’ll learn how to connect JDBC to SQL, understand each step clearly, and write clean, working code.
What is JDBC?
JDBC (Java Database Connectivity) is an API provided by Java that enables Java applications to:
- Connect to a database
- Execute SQL queries
- Retrieve and manipulate data
JDBC acts as a bridge between Java code and SQL databases.
Prerequisites
Before starting, make sure you have:
- Java JDK installed (Java 8 or above)
- Any SQL database (MySQL used in this example)
- Basic knowledge of Java & SQL
- MySQL Server running locally or remotely
- MySQL Connector (JDBC Driver)
JDBC Architecture (Simple Explanation)
Advertisement
JDBC works in four main steps:
- Load the JDBC Driver
- Establish a Database Connection
- Create & Execute SQL Statements
- Close the Connection
mysql
mysql-connector-j
8.3.0
CREATE DATABASE jdbc_demo;
USE jdbc_demo;
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);
Class.forName("com.mysql.cj.jdbc.Driver");
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/jdbc_demo";
String username = "root";
String password = "your_password";
try {
Connection connection = DriverManager.getConnection(
url, username, password
);
System.out.println("Database connected successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Jagnyadatta Dalai is a content creator on QueueVerse, sharing insights and expertise on various topics. With 0 published articles, they contribute valuable knowledge to the community.
View ProfileComments (1)
Please login to join the conversation
Login to CommentGreat! It helped lot sir. Thanks
Advertisement