我希望能够将列添加到具有相应类型的现有table
中。
这是我尝试的方式:
library("RMySQL")
# Connect to DB
v_db <- dbConnect(MySQL(),
user="USERNAME", password="PASSWORD",
dbname="DBNAME", host="localhost")
on.exit(dbDisconnect(v_db))
#Read in my new data (into R)
newcolumn <- read.csv("test.csv")
newcolumn
id datafornewcolumn
1 4
2 5
3 8
dbq <- dbSendQuery(v_db, "SELECT * FROM `EXISTINGTABLE`")
dbq <- fetch(dbq, n = -1)
dbq
id existing columns
1 ...
2 ...
3 ...
dbWriteTable(v_db, "EXISTINGTABLE", merge(dbq, newcolumn, by="id", all.x=TRUE), row.name=FALSE, overwrite=T)
但是在最后一个语句中,我用新的表覆盖了现有的表,从而丢失了所有相应的变量类型。
然后我尝试了一种解决方法。将新数据写入SQL中的新table
,然后将其合并到EXISTINGTABLE
中。但是,似乎我无法正确地做到这一点:
dbSendQuery(v_db, "create table workaround (id int not null primary key,
newcolumn DECIMAL(3,1))")
#write data into that new empty table called workaround --> works fine
dbWriteTable(v_db, "workaround", neu, row.name=FALSE, append=TRUE)
#something works...
dbSendQuery(v_db, "SELECT * FROM EXISTINGTABLE
LEFT JOIN workaround ON EXISTINGTABLE.id = workaround.id
UNION
SELECT * FROM EXISTINGTABLE
RIGHT JOIN workaround ON EXISTINGTABLE.id = workaround.id")
<MySQLResult:(29344,26,2)>
结果应如下所示:
EXISTINGTABLE
id existingcolumns datafornewcolumn
1 ... 4
2 ... 5
3 ... 8
答案 0 :(得分:1)
将列添加到现有表可以完成:
library(dbConnect) # *loads the packages Loading required package: RMySQL
Loading required package: DBI
Loading required package: methods
Loading required package: gWidgets*
mydb =dbConnect(MySQL(),user='root',password='newpass',dbname='database_name', host='localhost')
my_table <- dbReadTable(conn=mydb,name='table_name')
my_table$column_name<- NA # *creates new column named column_name and populates its value NA*
head(my_table) # *shows the data*
答案 1 :(得分:1)
您是否尝试使用带有ALTER TABLE语句的SQL修改表?
rs <- dbSendStatement(v_db, "ALTER TABLE table_name ADD COLUMN [...]")
dbHasCompleted(rs)
dbGetRowsAffected(rs)
dbClearResult(rs)
然后你可以简单地发送和UPDATE语句来添加新值。
首先使用dbExecute()
方法尝试...并在R控制台上尝试:
?dbExecute
或?dbSendStatement