Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create mysql table directly from CSV file using the CSV Storage engine?

I just learned that MySQL has a native CSV storage engine which stores data in a Comma-Separated-Value file per table.

Is it possible to create a table directly from a uploaded CSV file, something like:

CREATE TABLE USERS < PATH/USERS.CSV

where users.csv is uploaded by the user?

like image 905
Jonathan DS Avatar asked Apr 03 '12 17:04

Jonathan DS


People also ask

What is CSV storage engine in MySQL?

The CSV storage engine stores data in text files using comma-separated values format. The CSV storage engine is always compiled into the MySQL server. To examine the source for the CSV engine, look in the storage/csv directory of a MySQL source distribution.

How do I import a CSV file into MySQL Workbench table?

Importing CSV file using MySQL Workbench The following are steps that you want to import data into a table: Open table to which the data is loaded. Review the data, click Apply button. MySQL workbench will display a dialog “Apply SQL Script to Database”, click Apply button to insert data into the table.


2 Answers

I just discovered csvkit, which is a set of Unix command-line tools for CSV files. I installed it on my Mac with pip install csvkit. The command was:

csvsql --dialect mysql --snifflimit 100000 bigdatafile.csv > maketable.sql

You can alternatively provide a DB connection string and it can load the table directly.

like image 200
prototype Avatar answered Oct 17 '22 03:10

prototype


This is not possible. To create a table you need a table schema. What you have is a data file. A schema cannot be created with it.

What you can do is check if your file has a header row, and, in that case, you can manually create a table using that header row.

However, there is a way to generate a create table statement using a batch file as described by John Swapceinski in the comment section of the MySQL manual.

Posted by John Swapceinski on September 5 2011 5:33am.
Create a table using the .csv file's header:

#!/bin/sh
# pass in the file name as an argument: ./mktable filename.csv
echo "create table $1 ( "
head -1 $1 | sed -e 's/,/ varchar(255),\n/g'
echo " varchar(255) );"
like image 47
Shiplu Mokaddim Avatar answered Oct 17 '22 01:10

Shiplu Mokaddim