0% found this document useful (0 votes)
6 views

jdbc

Uploaded by

fantent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

jdbc

Uploaded by

fantent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

ava Database Connectivity (JDBC) - Detailed Explanation

JDBC (Java Database Connectivity) is an API that enables Java applications to


interact with relational databases. It allows querying and updating data using SQL.

1. JDBC Architecture Overview


JDBC consists of the following components:

Driver Manager – Loads database drivers and establishes connections.

Driver – A specific implementation for different databases (e.g., MySQL,


PostgreSQL).

Connection – Represents a connection to the database.

Statement – Used to execute SQL queries.

ResultSet – Stores the result of SELECT queries.

SQLException – Handles database-related exceptions.

2. JDBC Setup
Add JDBC Driver Dependency
For MySQL, include the JDBC driver in your project:

Maven Dependency (MySQL)

xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
Manually Download JDBC Driver Download the MySQL JDBC driver here.

3. Establishing a Database Connection


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

public class DatabaseConnection {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String user = "root"; // Database username
String password = "password"; // Database password

try (Connection conn = DriverManager.getConnection(url, user, password)) {


System.out.println("Connected to the database!");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Uses try-with-resources to close the connection automatically. ✔ Handles
SQLException properly.

4. Executing SQL Queries


a) Creating a Table
java
import java.sql.Connection;
import java.sql.Statement;

public class CreateTable {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Statement stmt = conn.createStatement()) {

String sql = "CREATE TABLE employees (id INT PRIMARY KEY, name
VARCHAR(50), salary DOUBLE)";
stmt.executeUpdate(sql);
System.out.println("Table created successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
b) Inserting Data
java
import java.sql.Connection;
import java.sql.Statement;

public class InsertData {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Statement stmt = conn.createStatement()) {

String sql = "INSERT INTO employees VALUES (1, 'John Doe', 50000)";
stmt.executeUpdate(sql);
System.out.println("Data inserted successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Retrieving Data with ResultSet
java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class FetchData {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees")) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double salary = rs.getDouble("salary");

System.out.println(id + " | " + name + " | " + salary);


}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
6. Using PreparedStatement (Avoid SQL Injection)
java
import java.sql.Connection;
import java.sql.PreparedStatement;

public class InsertPreparedStatement {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {


String sql = "INSERT INTO employees (id, name, salary) VALUES
(?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, 2);
pstmt.setString(2, "Alice");
pstmt.setDouble(3, 60000);
pstmt.executeUpdate();
System.out.println("Data inserted successfully using
PreparedStatement!");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
7. Updating and Deleting Records
Updating Records
java
String sql = "UPDATE employees SET salary = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, 70000);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
}
Deleting Records
java
String sql = "DELETE FROM employees WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, 2);
pstmt.executeUpdate();
}
8. Best Practices for JDBC
✔ Use PreparedStatement to avoid SQL injection. ✔ Always close database connections
using try-with-resources. ✔ Use connection pooling for better performance (via
HikariCP or Apache DBCP). ✔ Log errors properly instead of just printing them. ✔
Avoid hardcoded database credentials—use environment variables or configuration
files.

Next Steps
Since you're invested in Java and Spring Boot, learning Spring Data JPA would be a
great next step—it simplifies database interactions significantly! Let me know if
you'd like a guide on that 🚀.

What are best practices for using JDBC?How does JDBC compare to Hibernate?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy