简体   繁体   English

RPostgreSQL-如何将值从R导出到Postgresql表

[英]RPostgreSQL - how to export a value from r to postgresql table

my table(table1) in database 我在数据库中的table(table1)

Column |  Type   | Modifiers
--------+---------+-----------
 date1  | date    | not null
 line_1 | numeric | default 0
 line_2 | numeric | default 0
 line_3 | numeric | default 0
 line_4 | numeric | default 0
 line_5 | numeric | default 0

R console R控制台

> line1 <- 32+45
> line1
[1] 77

I want export these value (line1 = 77) into the table (table1) in line_1 column and date1 column should fill with present date minus 1 day. 我想将这些值(line1 = 77)导出到line_1列中的表(table1)中,并且date1列应填充当前日期减去1天。

I tried with the below command for updating line1 value, but i am getting an error 我尝试使用以下命令更新line1值,但出现错误

s <- dbGetQuery(con, "insert into table1 (line_1) values (line1)") s <-dbGetQuery(con,“插入到table1(line_1)值(line1)”)

Error in postgresqlExecStatement(conn, statement, ...) : RS-DBI driver: (could not Retrieve the result : ERROR: column "line1" does not exist LINE 1: insert into table1 (line_1) values (line1) ^ ) Warning message: In postgresqlQuickSQL(conn, statement, ...) : Could not create executeinsert into table1 (line_1) values (line1 ) postgresqlExecStatement(conn,statement,...)中的错误:RS-DBI驱动程序:(无法检索结果:错误:列“ line1”不存在LINE 1:插入到table1(line_1)值(line1)^)警告消息:在postgresqlQuickSQL(conn,statement,...)中:无法在表1(line_1)值(line1)中创建executeinsert

I think there are two issues in your code here - 我认为您的代码中有两个问题-

First, you probably should be using dbSendQuery() instead. 首先,您可能应该改用dbSendQuery()。 This is because you are sending a command to the Postgres server. 这是因为您正在向Postgres服务器发送命令。

Second, when you put text into double quotes, this usually tells R to interpret that as a string. 其次,当您将文本放在双引号中时,这通常会告诉R将其解释为字符串。 So when you are doing "insert into table1 (line_1) values (line1)", you are actually telling Postgres to insert "line1" into "line_1". 因此,当您执行“插入table1(line_1)值(line1)”时,实际上是在告诉Postgres将“ line1”插入“ line_1”。 What you want here if you want to add only one value is a paste command. 如果只想添加一个值,则在此处要执行的操作是粘贴命令。

Try this: 尝试这个:

dbSendQuery(con, paste0("insert into table1 (line_1) values (",line1,")"))

And for your date: 而对于您的约会:

date1<-Sys.Date()-1
dbSendQuery(con, paste0("insert into table1 (date1) values (",date1,")"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM