View source: R/convert_to_sql.R
| convert_to_sql | R Documentation |
Reads a CSV file and generates SQL statements to insert all rows. Optionally can also generate a CREATE TABLE statement. The function automatically infers column types (REAL for numeric, DATE for date strings matching YYYY-MM-DD format, TEXT otherwise).
convert_to_sql(input, output, create_table = FALSE)
input |
Character string. Path to the input CSV file. |
output |
Character string. Path to the output SQL file where the statements will be written. |
create_table |
Logical. If |
The function performs the following steps:
Reads the CSV file using read.csv() with
stringsAsFactors = FALSE
Infers SQL column types:
Numeric columns become REAL
Date columns (matching YYYY-MM-DD format) become DATE
All other columns become TEXT
If create_table = TRUE, generates a CREATE TABLE
statement using the base filename (without extension) as the table name
Generates INSERT INTO statements for each row
Writes all SQL statements to the output file
Single quotes in text values are escaped by doubling them (SQL standard). Numeric values are inserted without quotes, while text and date values are wrapped in single quotes.
Invisibly returns NULL. The function writes SQL statements to the specified output file.
# Convert a CSV file to SQL (INSERT statements only)
tmp_csv <- tempfile(fileext = ".csv")
tmp_sql <- tempfile(fileext = ".sql")
write.csv(
data.frame(id = 1:2, value = c("a", "b"), date = c("2024-01-01", "2024-02-02")),
tmp_csv,
row.names = FALSE
)
convert_to_sql(tmp_csv, tmp_sql)
# Convert a CSV file to SQL with CREATE TABLE statement
convert_to_sql(tmp_csv, tmp_sql, create_table = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.