JDBC, short for Java Database Connectivity, is a powerful API that enables Java applications to interact with relational databases. It provides a standardized way to connect, query, and manipulate data stored in various database management systems.
JDBC follows a four-layer architecture:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the database successfully!");
connection.close();
} catch (SQLException e) {
System.out.println("Connection failed: " + e.getMessage());
}
}
}
JDBC provides multiple ways to execute SQL queries:
import java.sql.*;
public class JDBCQuery {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
To further enhance your understanding of Java database operations, explore these related topics:
By mastering JDBC, you'll be able to create robust Java applications that efficiently interact with databases, opening up a world of possibilities for data-driven software development.