0

我正在尝试使用 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 = ?

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

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

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

4

2 回答 2

1

如果我理解您的问题,您希望为查询的 where 子句提供用户输入。你可能可以用 tidy eval 做一些心理体操,但paste0()似乎很容易解决:

param <- "'tag_col_content1'"

dbGetQuery(test_db, 
           paste0("select * from public.table1 where tag = ", param)) 
于 2021-08-04T23:19:29.497 回答
1

在 PostgreSQL 中,拼写占位符的官方方式是$1, $2, ... $9,... not ?。一些驱动程序会自动为您解析和转换查询,但显然不是这个。

当我用它$1代替时?,它可以工作。

于 2021-08-05T00:08:03.980 回答