0
点赞
收藏
分享

微信扫一扫

【记录】LaTex|LaTex调整算法、公式、表格内的字体大小(10种内置字号)

代码敲到深夜 2024-07-24 阅读 25

使用 JDBC 进行 Java 数据库操作详解

JDBC(Java Database Connectivity)是 Java 提供的一套用于执行 SQL 语句的 API,能够让 Java 应用程序与多种数据库进行交互。本文将详细介绍如何使用 JDBC 进行数据库操作,并通过代码示例展示各个步骤和知识点。

1. 准备工作

在开始使用 JDBC 进行数据库操作之前,我们需要准备一个 jdbc.properties 文件,包含数据库连接的相关信息。示例如下:

driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
password=root

2. 获取数据库连接

获取数据库连接是进行数据库操作的第一步。我们通过 DriverManager.getConnection 方法来获取数据库连接。

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {

    public static Connection getConnection() throws SQLException, IOException {
        // 从类路径下读取 jdbc.properties 文件
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(is);

        // 从属性文件中获取数据库连接信息
        String driverClass = properties.getProperty("driverClass");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        Class.forName(driverClass);

        // 关闭 InputStream
        closeResources(is);

        // 获取数据库连接并返回
        return DriverManager.getConnection(url, user, password);
    }
}

3. 执行 SQL 查询

使用 JDBC 执行 SQL 查询需要以下步骤:

  1. 创建 Connection 对象。
  2. 使用 Connection 对象创建 PreparedStatement 对象。
  3. 设置查询参数。
  4. 执行查询并获取结果集 ResultSet
  5. 处理结果集。
import java.sql.*;
import java.util.ArrayList;

public class JDBCUtils {
    public static <T> ArrayList<T> query(Class<T> clazz, String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        ArrayList<T> resultList = new ArrayList<>();
        try {
            // 获取数据库连接
            conn = getConnection();

            // 创建 PreparedStatement 对象
            ps = conn.prepareStatement(sql);

            // 设置 SQL 查询参数
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            // 执行查询并获取结果集
            resultSet = ps.executeQuery();

            // 获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            // 遍历结果集并映射到 Java 对象
            while (resultSet.next()) {
                T t = clazz.getDeclaredConstructor().newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = resultSet.getObject(i + 1);
                    String columnLabel = metaData.getColumnLabel(i + 1);

                    // 使用反射设置对象的属性值
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                resultList.add(t);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            closeResources(conn, ps, resultSet);
        }
        return resultList;
    }
}

4. 执行 SQL 更新

public class JDBCUtils {
    public static void update(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 获取数据库连接
            conn = getConnection();

            // 创建 PreparedStatement 对象
            ps = conn.prepareStatement(sql);

            // 设置 SQL 更新参数
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            // 执行更新
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            closeResources(conn, ps);
        }
    }
}

5. 关闭资源

关闭资源是防止资源泄漏的关键步骤。所有实现了 AutoCloseable 接口的资源(如 ConnectionStatementResultSet)都应该在使用后正确关闭。

public static void closeResources(AutoCloseable... resources) {
     for (AutoCloseable resource : resources) {
          if (Objects.nonNull(resource)) {
               try {
                    resource.close();
              } catch (Exception e) {
                    System.out.println(resource.getClass() + " not correctly closed!");
                    throw new RuntimeException(e);
              }
         }
    }
}

7. 使用示例

查询操作示例

假设有一个 User 类:

public class User {
    private int id;
    private String name;
    private String email;

    // getters and setters
}

可以使用 JDBCUtils.query 方法进行查询:

String sql = "SELECT id, name, email FROM users WHERE id = ?";
ArrayList<User> users = JDBCUtils.query(User.class, sql, 1);
for (User user : users) {
    System.out.println(user.getName());
}
更新操作示例

可以使用 JDBCUtils.update 方法进行更新:

String sql = "UPDATE users SET name = ? WHERE id = ?";
JDBCUtils.update(sql, "New Name", 1);

8. 总结

本文详细介绍了使用 JDBC 进行数据库操作的各个知识点,包括加载数据库驱动、获取数据库连接、执行查询和更新操作以及关闭资源。通过这些步骤,你可以更好地理解 JDBC 的工作原理,并熟悉 JDBC 的使用过程。

希望这篇博客能帮助你掌握 JDBC 的基础知识,为你的 Java 数据库操作奠定坚实的基础。

举报

相关推荐

0 条评论