groovy 如何遍历 postgresql 所有的用户表 ?

在 Groovy 中遍历 PostgreSQL 所有用户表,你可以使用 JDBC 连接数据库并执行 SQL 查询。以下是一个完整的示例:

Groovy 代码示例

groovy 复制代码
import groovy.sql.Sql

def config = [
    url: 'jdbc:postgresql://localhost:5432/your_database',
    user: 'your_username',
    password: 'your_password',
    driver: 'org.postgresql.Driver'
]

try {
    // 创建数据库连接
    def sql = Sql.newInstance(config.url, config.user, config.password, config.driver)
    
    // 查询所有用户表(public 模式)
    def tables = []
    sql.eachRow("""
        SELECT table_name
        FROM information_schema.tables
        WHERE table_schema = 'public'
          AND table_type = 'BASE TABLE'
        ORDER BY table_name
    """) { row ->
        tables << row.table_name
    }
    
    // 输出结果
    println "找到 ${tables.size()} 个用户表:"
    tables.each { table ->
        println "- ${table}"
        
        // 可选:遍历表结构
        def columns = []
        sql.eachRow("""
            SELECT column_name, data_type
            FROM information_schema.columns
            WHERE table_name = '${table}'
            ORDER BY ordinal_position
        """) { col ->
            columns << "${col.column_name} (${col.data_type})"
        }
        println "  列:${columns.join(', ')}"
    }
    
} catch (Exception e) {
    println "数据库操作失败:${e.message}"
    e.printStackTrace()
} finally {
    // 关闭连接
    if (sql) sql.close()
}

依赖配置

确保在 build.gradle 中添加 PostgreSQL 驱动依赖:

groovy 复制代码
dependencies {
    implementation 'org.postgresql:postgresql:42.6.0'
}

关键说明

  1. 数据库连接 :使用 Sql.newInstance() 创建连接,需要替换为你的数据库 URL、用户名和密码。
  2. 查询用户表 :通过 information_schema.tables 系统视图过滤出 public 模式下的普通表(BASE TABLE)。
  3. 遍历结果 :使用 eachRow() 方法处理查询结果集,将表名收集到列表中。
  4. 可选表结构:示例中包含了获取表列信息的代码,可根据需要启用。
  5. 异常处理 :使用 try-catch-finally 确保资源正确关闭。

其他模式的表

如果需要查询其他模式(如 myschema)的表,修改查询条件:

groovy 复制代码
WHERE table_schema = 'myschema'

如果需要查询所有模式的表,移除 table_schema 过滤条件:

groovy 复制代码
WHERE table_type = 'BASE TABLE'

这个脚本可以作为自动化数据库检查或元数据收集工具的基础。

相关推荐
羊锦磊1 小时前
[ Redis ] SpringBoot集成使用Redis(补充)
java·数据库·spring boot·redis·spring·缓存·json
倔强的石头_1 小时前
【金仓数据库】ksql 指南(三) —— 创建与管理表空间和模式
数据库
程序新视界3 小时前
详解MySQL两种存储引擎MyISAM和InnoDB的优缺点
数据库·后端·mysql
半路_出家ren3 小时前
设计一个学生管理系统的数据库
linux·数据库·sql·mysql·网络安全·数据库管理员
金仓拾光集5 小时前
筑牢风控生命线:金仓数据库替代MongoDB,重构证券融资融券业务的数据基石
数据库·mongodb·信创·1024程序员节·kingbasees·国产化替代
那我掉的头发算什么5 小时前
【数据库】navicat的下载以及数据库约束
android·数据库·数据仓库·sql·mysql·数据库开发·数据库架构
纪伊路上盛名在5 小时前
如何批量获取蛋白质序列的所有结构域(domain)数据-2
数据库·人工智能·机器学习·统计·计算生物学·蛋白质
2301_772093567 小时前
高并发webserver_interview
运维·服务器·数据库·后端·网络协议·mysql·wireshark
大G的笔记本8 小时前
MySQL 大表查询优化、超大分页处理、SQL 慢查询优化、主键选择
数据库·sql·mysql
Lear8 小时前
Redis 持久化机制
数据库