假设我正在使用starwars数据集,并尝试在Mysql数据库中创建表(使用copy_to)
library(tidyverse)
data <- starwars %>%
select(name, skin_color)
data
# A tibble: 87 x 2
name skin_color
<chr> <chr>
1 Luke Skywalker fair
2 C-3PO gold
3 R2-D2 white, blue
4 Darth Vader white
5 Leia Organa light
6 Owen Lars light
7 Beru Whitesun lars light
8 R5-D4 white, red
9 Biggs Darklighter light
10 Obi-Wan Kenobi fair
# … with 77 more rows
conn <- DBI::dbConnect(RMariaDB::MariaDB(),
host = "myhost",
user = "myuser",
password = "mypass",
db = "mydb")
copy_to(conn, data, temporary = FALSE, overwrite = TRUE)
问题在于字符列创建为TEXT列,但正确的定义应为VARCHAR。
DESC table data
`data` (
`name` TEXT NULL,
`skin_color` TEXT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
如何强制使用varchar而不是文本?
答案 0 :(得分:0)
这可能不是理想的解决方案,但是在运行R脚本之前,您始终可以先尝试在MariaDB中创建目标表。然后,将copy_to
设置为false的情况下调用overwrite
:
来自MariaDB:
CREATE TABLE data (
name varchar(255),
skin_color varchar(255)
);
来自R:
copy_to(conn, data, temporary=FALSE, overwrite=FALSE)