import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ResultSetExample {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1. 注册 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 打开连接
            String url = "jdbc:mysql://localhost:3306/your_database";
            String user = "your_username";
            String password = "your_password";
            conn = DriverManager.getConnection(url, user, password);
            // 3. 创建语句对象
            stmt = conn.createStatement();
            // 4. 执行查询并获取结果集
            String sql = "SELECT id, name, age FROM your_table";
            rs = stmt.executeQuery(sql);
            // 5. 处理结果集
            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 (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}Class.forName() 方法加载 MySQL 的 JDBC 驱动程序。DriverManager.getConnection() 方法建立与数据库的连接,需要提供数据库 URL、用户名和密码。Connection 对象创建 Statement 对象,用于执行 SQL 语句。Statement 对象的 executeQuery() 方法执行 SQL 查询,并返回一个 ResultSet 对象。ResultSet 对象的 next() 方法遍历查询结果,并使用 getInt() 和 getString() 等方法获取列值。finally 块中关闭 ResultSet、Statement 和 Connection,确保资源被正确释放。上一篇:java 异步调用
下一篇:java unix时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站