📅  最后修改于: 2023-12-03 14:43:05.209000             🧑  作者: Mango
JDBC stands for Java Database Connectivity. It is a Java API that provides a standard interface for connecting Java applications to databases. SQL stands for Structured Query Language, which is a programming language used for managing and manipulating relational databases. In combination, JDBC and SQL allow Java programs to access and manipulate database information.
Portability: JDBC API is platform-independent and works on all major operating systems.
Scalability: JDBC driver managers allow you to connect to different databases and switch between them as needed.
Flexibility: JDBC API provides different types of JDBC drivers that can be used to access databases.
There are four JDBC components:
Driver Manager: Manages the loaded drivers and establishes the database connection.
Driver: Provides a connection to a specific data source.
Connection: Represents a connection to the database.
Statement: Represents an SQL statement that is executed against the database.
SQL commands are used to manage and manipulate the data in a relational database. Some of the most commonly used SQL commands are:
SELECT column1, column2, ... FROM table_name;
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
DELETE FROM table_name WHERE condition;
Here is a simple example of a Java program that demonstrates the use of JDBC and SQL to retrieve data from a database:
import java.sql.*;
public class JdbcExample {
static final String DB_URL = "jdbc:mysql://localhost/mydatabase";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM employees")) {
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}