Java Database Connectivity (JDBC)

Connecting to Databases using JDBC:

Java Database Connectivity (JDBC) is a vital API that facilitates seamless communication between Java applications and databases. It enables developers to establish connections, execute SQL queries, and retrieve data from databases.

Example of Connecting to a Database:

import java.sql.*;

public class JdbcExample {
public static void main(String[] args) {
String url = “jdbc:mysql://localhost:3306/mydatabase”;
String username = “username”;
String password = “password”;

try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println(“Connected to the database!”);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Executing SQL Queries:

JDBC empowers developers to execute SQL queries and interact with the database effectively. You can perform operations like INSERT, SELECT, UPDATE, and DELETE to manage data.

Example of Executing SQL Query:

try (Statement statement = connection.createStatement()) {
String sql = “SELECT * FROM employees”;
ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {
int id = resultSet.getInt(“id”);
String name = resultSet.getString(“name”);
double salary = resultSet.getDouble(“salary”);
System.out.println(“Employee ID: ” + id + “, Name: ” + name + “, Salary: ” + salary);
}
} catch (SQLException e) {
e.printStackTrace();
}

PreparedStatement for Preventing SQL Injection:

To prevent SQL injection attacks, JDBC provides PreparedStatement, which allows parameterized queries and automatically escapes user input.

Example of PreparedStatement:

String name = “John”;
int age = 25;

String sql = “SELECT * FROM employees WHERE name = ? AND age = ?”;
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);

ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
// process the result set
}
} catch (SQLException e) {
e.printStackTrace();
}

Conclusion:

Java Database Connectivity (JDBC) is an essential component for Java applications to interact with databases effortlessly. By establishing connections, executing SQL queries, and leveraging PreparedStatement to prevent SQL injection, developers can build secure and robust database-driven applications. Embrace the power of JDBC, and let your Java applications communicate seamlessly with databases, making data management a breeze!

Leave a Comment