欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > groovy 如何遍历 postgresql 所有的用户表 ?

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

2025/5/16 21:08:38 来源:https://blog.csdn.net/belldeep/article/details/147992635  浏览:    关键词:groovy 如何遍历 postgresql 所有的用户表 ?

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

Groovy 代码示例

import groovy.sql.Sqldef 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_nameFROM information_schema.tablesWHERE 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_typeFROM information_schema.columnsWHERE 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 驱动依赖:

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)的表,修改查询条件:

WHERE table_schema = 'myschema'

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

WHERE table_type = 'BASE TABLE'

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词