Java Database Connectivity (JDBC) is a powerful Java API that enables seamless interaction between Java applications and relational databases. It provides a standardized way to connect, query, and manipulate data stored in various database management systems.
To connect to a database using JDBC, follow these steps:
import java.sql.*;
public class JDBCExample {
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("Error connecting to the database: " + e.getMessage());
}
}
}
Once connected, you can execute SQL queries using Statement or PreparedStatement objects. Here's an example of a simple query:
String sql = "SELECT * FROM users";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
resultSet.close();
statement.close();
JDBC is a crucial component in Java Enterprise Edition (Java EE) applications. It seamlessly integrates with other Java EE technologies, such as Servlets and JavaServer Pages (JSP), enabling robust database-driven web applications.
Java Database Connectivity provides a powerful and flexible way to interact with databases in Java applications. By mastering JDBC, developers can create sophisticated data-driven applications that efficiently manage and manipulate database information.
For more advanced database operations, consider exploring topics like Java SQL Queries and Java Prepared Statements.