Home > Java > javaTutorial > body text

How does Java database connection use JDBC API?

王林
Release: 2024-04-16 16:12:02
Original
1053 people have browsed it

Java Database Connectivity (JDBC) is an API for Java programs to interact with databases. To establish a JDBC connection, you need to: 1. Import the JDBC driver JAR file. 2. Load and register the driver. 3. Create a Connection object. JDBC allows SQL query and update operations and provides PreparedStatement for performing updates. After all operations are completed, the JDBC connection should be closed to release resources. Using JDBC, you can easily interact with the database such as inserting, querying, and updating records.

Java数据库连接如何使用JDBC API?

Java Database Connection: JDBC API Practical Guide

JDBC (Java Database Connectivity) is an API for Java programs to interact with databases. It provides a standard way to access different databases including MySQL, Oracle, PostgreSQL, etc.

Set up a JDBC connection

To establish a JDBC connection to the database, you need to:

  1. Import the JDBC driver JAR file.
  2. Load and register the driver.
  3. Create a Connection object.
import java.sql.*;

public class JdbcExample {

    public static void main(String[] args) {
        // 数据库凭据
        String url = "jdbc:mysql://localhost:3306/database_name";
        String username = "root";
        String password = "password";

        // 加载和注册驱动程序
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        // 创建连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }

        // 使用连接执行 SQL 查询或更新操作
        // ...
    }
}
Copy after login

Execute SQL queries

Once the connection is established, you can execute SQL queries.

// 创建一个 Statement 对象
Statement statement = connection.createStatement();

// 执行查询并获取结果集
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");

// 遍历结果集
while (resultSet.next()) {
    // 获取列值
    int id = resultSet.getInt("id");
    String name = resultSet.getString("name");
    
    // 打印结果
    System.out.println("Id: " + id + ", Name: " + name);
}
Copy after login

Performing SQL Updates

To perform SQL update operations (such as inserting, updating, or deleting records), you can use PreparedStatement.

// 创建一个 PreparedStatement
String sql = "INSERT INTO table_name (name, age) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);

// 设置参数
statement.setString(1, "John Doe");
statement.setInt(2, 30);

// 执行更新
int rowCount = statement.executeUpdate();
Copy after login

Close the JDBC connection

After completing all operations, be sure to close the JDBC connection to release resources.

try {
    connection.close();
} catch (SQLException e) {
    e.printStackTrace();
}
Copy after login

Practical case

Suppose you have a customers table containing the following columns:

  • id (ID)
  • name(name)
  • age(age)

Using JDBC, you can create a Java program to insert a new customer:

// 添加新客户
String sql = "INSERT INTO customers (name, age) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "Jane Doe");
statement.setInt(2, 25);
int rowCount = statement.executeUpdate();

// 验证是否成功
if (rowCount > 0) {
    System.out.println("新客户已添加。");
}
Copy after login

Then, you can Verify that the insertion was successful by outputting the records in the customers table:

// 输出客户
ResultSet resultSet = statement.executeQuery("SELECT * FROM customers");
while (resultSet.next()) {
    int id = resultSet.getInt("id");
    String name = resultSet.getString("name");
    int age = resultSet.getInt("age");
    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age);
}
Copy after login

The above is the detailed content of How does Java database connection use JDBC API?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template