从 rmysql 生成时 SQL 查询包含 'c('

SQL query contains 'c(' when being generated from rmysql

我正在使用库 RMySQL 生成 SQL 语句

query <- sprintf("foo", paste(mydf, collapse = "', '",sep = ','))

当我查看查询时,它似乎将所有内容都放在括号中,例如,一列将包含单项 10.50, 20.50, 50.33,但是当我查看 SQL 时,它显示为c(10.50,20.50, 50.33) 导致我的 SQL 崩溃。有谁知道为什么?

可重现的例子

mydf <- data.frame(
   X = sample(1:10),
   Y = sample(c("yes", "no"), 10, replace = TRUE)
 )

 # Construct the update query by looping over the data fields
 query <- sprintf("INSERT INTO feedback (X,Y) VALUES ('%s')",
                  paste(mydf, collapse = "', '",sep = ','))


> cat(query)
INSERT INTO feedback (X,Y) VALUES ('c(8, 6, 10, 9, 3, 4, 5, 7, 2, 1)', 'c(1, 2, 1, 2, 2, 1, 1, 1, 2, 2)')

谢谢

如上所述,考虑使用 dbWriteTable() to import a dataframe to an existing MySQL database table. Dataframe columns should match database table's column names and types (or coercible types) or types specified using a named list in its field.types 参数:

dbWriteTable(conn, "MyTable", mydf, row.names = FALSE, append = TRUE) 

此外,dataframe 不需要详尽无遗地填充数据库中的每个当前列 table,因此省略任何自动字段,如自动增量 ID 和时间戳。


甚至考虑使用暂存临时 table 定期清理可能需要避免重复(w/ NOT IN or NOT EXISTS or LEFT JOIN / IS NULL 查询) and/or 不匹配 df 中不同的命名列或附加列在数据库中 table:

dbSendQuery(conn, "DELETE FROM MyTempTable")  # OR USE overwrite = TRUE in next line
dbWriteTable(conn, "MyTempTable", mydf, row.names = FALSE, append = TRUE) 
dbSendQuery(conn, "INSERT INTO MyTable (Col1, Col2, Col3, ...)
                   SELECT Col1, Col2, Col3 ... FROM MyTempTable")