在 R 中,如何使用参数将 PostgreSQL 列内容传递给 dbGetQuery

In R, how to pass PostgreSQL column contents to dbGetQuery using param

我正在尝试使用 dbGetQuery() 在 R 中查询我的 PostgreSQL 数据库。以下是我到目前为止所做的:

这条命令运行顺利通过我把它放在这里只是为了展示如何查询数据库

test_db = dbPool(drv = dbDriver("PostgreSQL", max.con = 100),
           dbname = "TEST",
           host = "localhost",
           user = "postgres",
           password = "password",
           idleTimeout = 3600000
        )    

此命令运行有错误

dbGetQuery(test_db, 
       "select * from public.table1 where tag = ?", 
       params = 'tag_col_content1') 

Error in postgresqlExecStatement(conn, statement, ...) : 
RS-DBI driver: (could not Retrieve the result : ERROR:  syntax error at end of input
LINE 1: ...lect * from public.table1 where tag = ?
                                                  ^
)
NULL
Warning message:
In postgresqlQuickSQL(conn, statement, ...) :
  Could not create execute: select * from public.table1 where tag = ?

我不得不怀疑它与 double/single 引号有关,但无法弄清楚到底是什么。我还尝试了以下有效:

dbGetQuery(test_db, 
       "select * from public.table1 where tag = 'tag_col_content1'") 

请注意,将值传递给 SQL 语句对我来说很重要,因为最终这一行将在 Rshiny 中以交互方式使用。非常感谢

如果我理解你的问题,你想向查询的 where 子句提供用户输入。您可能可以使用 tidy eval 做一些心理体操,但 paste0() 似乎是一个简单的修复方法:

param <- "'tag_col_content1'"

dbGetQuery(test_db, 
           paste0("select * from public.table1 where tag = ", param)) 

在 PostgreSQL 中,占位符的官方拼写方式是 </code>、<code>、... </code>、... 而不是 <code>?。有些驱动程序会自动为您解析和转换查询,但显然不是这个。

当我用 </code> 代替 <code>? 时,它起作用了。