问题描述
我的 R 程序在查询 PostgreSQL 数据库时遇到问题。这是代码
### Here we assume that myuser,mypassword,db,host_db and db_port
### have been defined in previous lines in the code
db_con <- dbConnect(
RPostgres::Postgres(),dbname = db,host = host_db,port = db_port,user = myuser,password = mypassword
)
###
###
### Running the query
query <- dbSendQuery(
db_con,paste(
"select t1.username,count(*) as query_cnt ","from public.app_queries as t1 ","group by t1.username ","order by query_cnt desc ","limit 50",sep = ""
)
)
###
### Fetching all rows from the ResultSet by setting n = -1
result <- dbFetch(query,n = -1)
###
### . . . using result here in my code . . .
###
### Once the result is no more needed,according to the documentation
### I have to clear the ResultSet before closing the connection.
dbClearResult(result)
###
### And finally close the connection to the database.
dbDisconnect(db_con)
问题是上面代码中的 dbClearResult(result)
失败并显示以下错误消息:
Error in (function (classes,fdef,mtable) :
unable to find an inherited method for function 'dbClearResult' for signature '"data.frame"'
我真的开始学习如何将 R 连接到 PostgreSQL。我从错误消息中了解到,显然在我的代码中创建的 ResultSet 是 data.frame
而 dbClearResult
不喜欢那样。我查看了 dbSendQuery
文档,但没有找到任何必须用于创建 ResultSet 的特定类型。
能否请您澄清一下并指出我的错误在哪里?
解决方法
dbClearResult
适用于 query
对象,而不适用于获取的 result
(这是一个 dataframe
,因此是错误消息):
query <- dbSendQuery(db_con,...)
result <- dbFetch(query,n = -1)
dbClearResult(query)
dbDisconnect(db_con)