如何从 R 中的数据库中获取列名?

How to get the column names from Database in R?

如何使用 R 获取唯一特定的 table 列名称?

示例代码:

df<-dbgetQuery(con,"select * from table 1 limit 100")
colnames(df)

上述查询是否有其他替代方法?

找到解决方案并将使用以下查询获取列名。

dbGetQuery(con,"SELECT column_name
+ FROM information_schema.columns
+ WHERE table_schema = 'your schema'
+   AND table_name   = 'table name'") ##ORDER  BY ordinal_position; to orderby

示例查询:

dbGetQuery(con,"SELECT column_name, data_type
+ FROM   information_schema.columns
+ WHERE  table_name = 'data 1'
+ ORDER  BY ordinal_position")

两个查询都运行良好。

为了完整起见,我 post 用于检索 table 概述的完整代码 + table 类型的列的概述:

library(RPostgres)

# login
your_connection <- dbConnect(Postgres(),
                             host = '*your-host-address*',
                             port = *your-port-four-digits*,
                             user = '*your-username*',
                             password = 'your-password*',
                             sslmode = 'require',
                             dbname = '*name-of-database*')

# send request to get overview of tables
res <- dbSendQuery(your_connection, "select distinct table_schema
                   from information_schema.tables
                   where table_type ='VIEW'
                   or table_type ='FOREIGN TABLE'
                   order by table_schema")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data

# send request to get overview of tables in a table schema
res <- dbSendQuery(your_connection, "select distinct table_name
                   from information_schema.columns
                   where table_schema='*your-table-name*'
                   order by table_name")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data

# send request to get overview of columns of a table
res <- dbSendQuery(your_connection, "select distinct column_name, data_type
                   from information_schema.columns
                   where table_name ='*your-table-name*'
                   order by column_name")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data