从数据框中插入RMySQL [英] Insert in RMySQL from data frame

查看:276
本文介绍了从数据框中插入RMySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用RMySQL将数据添加到MySQL表中。我只需要一次添加一行,它不工作。我想要做的是这样的。

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

所以我在做的是我有价值在数据帧中被命名为数据,我需要把它们放入mysql表中。在此之前,我将检查它们是否已经在表中,如果不是,那么我将添加它们,但是这样做是不行的。数据从.csv文件中读取 read.csv

解决方案

您可以使用粘贴来构造实际查询。

  dat< ;  - 矩阵(1:4,2,2)
query< - paste(INSERT INTO names VALUES(,data [1,1],,,data [1,2],) )
查询
#[1]INSERT INTO名称VALUES(1,3)
dbGetQuery(con,query)

#如果有很多的列可能是乏味的...
#所以我们也可以使用粘贴来一次添加所有的值。
查询< - 粘贴(INSERT INTO名称VALUES(,粘贴(数据[1,],collapse =,),))
查询
#[1] INSERT INTO name VALUES(1,3)


Im trying to add data to MySQL table by using RMySQL. I only need to add one row at a time and it's not working. What I'm trying to do is this.

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

so what I'm doing is that I have values in data frame that is named as "data" and I need to put them into mysql table. before that I will check them if they are already in the table or not and if they are not then I will add them, but that way it isn't working. The data is read from .csv file by read.csv .

解决方案

You can use paste to construct that actual query.

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 )"

这篇关于从数据框中插入RMySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆