当前位置: 首页 > article >正文

使用 Java 执行 SQL 语句和存储过程

使用 Java 执行 SQL 语句和存储过程,通常有两种主要的方式:使用 JDBC(Java Database Connectivity)或者通过框架如 Spring Data JPA、MyBatis 等。

1. 使用 JDBC 执行 SQL 语句

JDBC 是 Java 操作数据库的标准 API。以下是通过 JDBC 执行 SQL 语句的基本步骤:

  1. 加载数据库驱动程序。
  2. 获取数据库连接。
  3. 创建 StatementPreparedStatement 对象。
  4. 执行 SQL 语句。
  5. 处理查询结果(如果有)。
  6. 关闭资源。

示例代码:执行普通的 SQL 查询

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String user = "root";
        String password = "your_password";
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 1. 加载 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取数据库连接
            conn = DriverManager.getConnection(url, user, password);

            // 3. 创建 Statement 对象
            stmt = conn.createStatement();

            // 4. 执行 SQL 查询
            String sql = "SELECT * FROM your_table";
            rs = stmt.executeQuery(sql);

            // 5. 处理查询结果
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

2. 使用 JDBC 执行存储过程

存储过程是预编译的 SQL 代码,可以被数据库直接调用。通过 JDBC 调用存储过程的步骤和执行普通 SQL 类似,但需要使用 CallableStatement 对象。

步骤:

  1. 加载数据库驱动程序。
  2. 获取数据库连接。
  3. 创建 CallableStatement 对象,传入存储过程的 SQL 语句。
  4. 设置存储过程的参数。
  5. 执行存储过程。
  6. 获取存储过程的输出结果。
  7. 关闭资源。

示例代码:调用存储过程

假设有一个存储过程如下:

CREATE PROCEDURE getEmployeeInfo(IN emp_id INT)
BEGIN
    SELECT * FROM employees WHERE id = emp_id;
END

Java 代码如下:

import java.sql.*;

public class JdbcStoredProcedureExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String user = "root";
        String password = "your_password";
        
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;

        try {
            // 1. 加载 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取数据库连接
            conn = DriverManager.getConnection(url, user, password);

            // 3. 创建 CallableStatement 对象,调用存储过程
            String sql = "{CALL getEmployeeInfo(?)}";
            stmt = conn.prepareCall(sql);

            // 4. 设置存储过程的输入参数
            stmt.setInt(1, 123);  // 假设查询员工 ID 为 123 的员工信息

            // 5. 执行存储过程
            rs = stmt.executeQuery();

            // 6. 获取存储过程的结果
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 使用 Spring JDBC 执行 SQL 语句

如果你使用 Spring 框架,可以通过 Spring 的 JDBC 模板简化操作。Spring JDBC 模板提供了更高级的封装,使得执行 SQL 操作更加简洁。

示例代码:使用 Spring JDBC 模板执行 SQL 查询

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class SpringJdbcExample {
    public static void main(String[] args) {
        // 设置数据源
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/your_database");
        dataSource.setUsername("root");
        dataSource.setPassword("your_password");

        // 创建 JdbcTemplate 对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        // 执行查询
        String sql = "SELECT * FROM your_table";
        jdbcTemplate.query(sql, (rs, rowNum) -> {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println("ID: " + id + ", Name: " + name);
            return null;
        });
    }
}

4. 使用 Spring JDBC 执行存储过程

Spring 也支持执行存储过程,可以通过 JdbcTemplateSimpleJdbcCall 类来实现。

示例代码:使用 Spring 执行存储过程

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.Types;

public class SpringStoredProcedureExample {
    public static void main(String[] args) {
        // 设置数据源
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/your_database");
        dataSource.setUsername("root");
        dataSource.setPassword("your_password");

        // 创建 SimpleJdbcCall 对象
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource)
            .withProcedureName("getEmployeeInfo")  // 存储过程名
            .declareParameters(new SqlParameter("emp_id", Types.INTEGER));

        // 执行存储过程
        jdbcCall.execute(123);  // 假设查询员工 ID 为 123 的信息
    }
}

总结

  • JDBC:最基础的数据库操作方法,适合不使用任何框架时。
  • Spring JDBC:适合在 Spring 框架下使用,简化了数据库操作并处理了许多细节。
  • 存储过程:可以通过 CallableStatement 执行存储过程,存储过程本身由数据库管理,能够提高性能。

http://www.kler.cn/a/578085.html

相关文章:

  • [含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
  • Java面试第九山!《SpringBoot框架》
  • Golang:实时消息交互系统
  • 物联网中 对设备监测和设备控制
  • C语言学习笔记-进阶(7)字符串函数3
  • 树莓派学习(一)——3B+环境配置与多用户管理及编程实践
  • SQL注入的原理及详细运用
  • 在 Docker 中搭建GBase 8s主备集群环境
  • Banana Pi OpenWRT One Wifi6 OpenWrt社区官方开源路由器评测
  • mysql忘记初始临时密码解决方法
  • 夏门大学DeepSeek 手册:从社会大众到高校及企业的全面应用实践研究(附 PDF 下载)
  • 2025年渗透测试面试题总结-长某亭科技-安全服务工程师(二面) (题目+回答)
  • react任务调度(简单版)和最小堆算法
  • Leetcode 62: 不同路径
  • 掌握Kubernetes Network Policy,构建安全的容器网络
  • 蓝桥备赛(13)- 链表和 list(下)
  • Linux(ubuntu)环境下部署The Fuck项目的方法(保姆级教程)
  • Feign 核心规则与最佳实践:避免入坑指南
  • 【哇! C++】类和对象(三) - 构造函数和析构函数
  • LeetCodehot 力扣热题100 跳跃游戏2