-->

从数据帧中插入RMySQL(Insert in RMySQL from data frame)

2019-07-20 12:45发布

我试着用RMySQL将数据添加到MySQL表。 我只需要一次添加一行,它不工作。 我想要做的就是这个。

dbGetQuery(con,"INSERT INTO names VALUES(data[1,1], data[1,2])")

所以我在做什么是我在数据帧被命名为“数据”的价值观,我需要把它们放进MySQL表。 在此之前,我会检查他们是否已经在表或不和,如果他们不那么我会加他们,但这样,它不工作。 该数据是从.csv文件读取read.csv

Answer 1:

您可以使用paste来构建实际的查询。

dat <- matrix(1:4, 2, 2)
query <- paste("INSERT INTO names VALUES(",data[1,1], ",", data[1,2], ")")
query
#[1] "INSERT INTO names VALUES( 1 , 3 )"
dbGetQuery(con, query)

# If there are a lot of columns this could be tedious...
# So we could also use paste to add all the values at once.
query <- paste("INSERT INTO names VALUES(", paste(data[1,], collapse = ", "), ")")
query
#[1] "INSERT INTO names VALUES( 1, 3 )"


Answer 2:

您可以尝试使用:

dbWriteTable(names, data[1,],append=True)

作为DBI包细节



文章来源: Insert in RMySQL from data frame