Welcome to the Java JDBC tutorial! This guide will help you get started with using JDBC (Java Database Connectivity) to connect and interact with databases from Java applications.

JDBC 简介

JDBC is a Java API that allows you to connect to various databases, such as MySQL, PostgreSQL, Oracle, and more. It provides a standard way to access and manipulate data in databases from Java applications.

安装 JDBC 驱动

Before you can use JDBC, you need to install the JDBC driver for the database you want to connect to. Each database vendor provides a JDBC driver that you can download and add to your project's classpath.

示例:MySQL JDBC 驱动

To connect to a MySQL database, you'll need to download the MySQL JDBC driver and add it to your project's classpath. You can download the driver from the MySQL website.

连接数据库

To connect to a database using JDBC, you'll need to use the DriverManager.getConnection() method. This method takes three parameters: the JDBC URL, username, and password.

String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";

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

执行 SQL 查询

Once you have a connection to the database, you can use JDBC to execute SQL queries. You can use the Statement or PreparedStatement class to execute queries.

示例:查询数据

String query = "SELECT * FROM users";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
    String name = rs.getString("name");
    String email = rs.getString("email");
    System.out.println(name + " - " + email);
}

rs.close();
stmt.close();
conn.close();

插入、更新和删除数据

JDBC also allows you to insert, update, and delete data in a database.

示例:插入数据

String insertQuery = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john.doe@example.com");

pstmt.executeUpdate();

pstmt.close();
conn.close();

总结

This tutorial provided an overview of Java JDBC, including how to connect to a database, execute SQL queries, and insert, update, and delete data. For more information, please visit our JDBC 实践指南.

相关资源

[center][Golden_Retriever]