How to write out dataframe mtcars to mtcars.sql
file ?
So I can import the sql file to MySql manual.
(xx.write
just wished function )
library(tidyverse)
xx.write(mtcars,'mtcars.sql')
How to write out dataframe mtcars to mtcars.sql
file ?
So I can import the sql file to MySql manual.
(xx.write
just wished function )
library(tidyverse)
xx.write(mtcars,'mtcars.sql')
2
Answers
I’ve shamelessly stolen margusl’s solution and wrapped it into a utility function:
Use it like this:
This will create a file
mtcars.sql
with the following contents:Or you can explicitly specify the table and/or file path:
You can get SQL insert script from
DBI::sqlAppendTable()
; if you need to create that table first, there’s alsoDBI::sqlCreateTable()
.For simple frames like
mtcars
,sqlCreateTable()
andsqlAppendTable()
outputs are identical for both SQLite and MySQL/MariaDB. I´m not really sure if the same applies to all corner cases, but you could also just switch to MariaDB DBI interface to play it safe (this is what you should be using for MySQL too asRMySQL
is being phased out). Though of course you’d need to have access to MySQL or MariaDB instance for this:Created on 2024-07-11 with reprex v2.1.0