JDBC Introduction

What is JDBC?

JDBC (Java Database Connectivity) is an API (Application Programming Interface) that allows Java applications to interact with databases. It provides methods to connect, execute queries, retrieve data, and manipulate databases using Java code.


Why is JDBC?

Java applications need a way to communicate with databases like MySQL, PostgreSQL, Oracle, and SQL Server. JDBC acts as a bridge between Java programs and relational databases.

JDBC Process (Step-by-Step):

To interact with a database using JDBC, follow these 5 steps:


1. Import JDBC Packages

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

2. Establish Connection

Use the DriverManager.getConnection() method.

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");

3. Create a Statement

A Statement object is used to execute SQL queries.

Statement stmt = con.createStatement();

4. Execute SQL Query

Use executeQuery() for SELECT statements and executeUpdate() for INSERT, UPDATE, DELETE.

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

5. Process the Results

Retrieve data from the ResultSet object.

while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

6. Close the Connection

Always close database connections to free up resources.

con.close();
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
con.close();

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.