Create table from CSV

Print
PDF
I needed to create SQLite tables from CSV files.
These CSV files contained the names of columns in the front line.

So I created a PHP script from the command line that I put at your disposal. You can easily modify this script to suit your needs.
To use:
php-q tableFromCsv.php SQLiteDatabase tableName CSV_Filename [separator] [delimitor]
or
. / tableFromCsv.php SQLiteDatabase tableName CSV_Filename [separator] [delimitor]

SQLiteDatabase: filename of the database SQLite2 (with absolute or relative path)
tableName: name of the new table
CSV_Filename name of the CSV file to import (with absolute or relative path)
separator: separator character data (Optional default '; ")
delimitor: string delimiter (Optional, default empty)

Here's the script:
# '/ usr / local / bin / php
/ *
* Creates a table from a CSV file whose first line contains column titles
*
* Usage:
* Php-q tableFromCsv.php SQLiteDatabase tableName CSV_Filename [separator] [delimitor]
*. / TableFromCsv.php SQLiteDatabase tableName CSV_Filename [separator] [delimitor]
* /

if (count ($ _SERVER [ 'argv'])>= 4) (
$ DatabaseFile = $ _SERVER [ 'argv'] [1];
$ tableName = $ _SERVER [ 'argv'] [2];
$ csvFilename = $ _SERVER [ 'argv'] [3];

if (isset ($ _SERVER [ 'argv'] [4])) $ separator = $ _SERVER [ 'argv'] [4] else $ separator = ',';
if (isset ($ _SERVER [ 'argv'] [5])) $ delimiter = $ _SERVER [ 'argv'] [5]; else $ delimiter = null;

if ($ db = sqlite_open ($ DatabaseFile, 0666, $ sqliteerror)) (
$ row = 0;
$ handle = fopen ($ csvFilename, "r");
while (($ data = fgetcsv ($ handle, 0, $ separator))! == FALSE) (
if ($ row) (
if (! sqlite_query ($ db, "CREATE TABLE". $ tableName. "(". implode ( '', $ data ().");"))
echo "The table creation failed.";
exit;
)
Else ()
$ tempTab = array ();
foreach ($ data as $ val) (
$ val = utf8_decode ($ val);
$ val = str_replace ("''", "", $ val);
$ tempTab [] = "". sqlite_escape_string ($ val). " '";
)
$ q = "INSERT INTO". $ tableName. "VALUES (". implode ( "", $ tempTab ).");";
sqlite_query ($ db, $ q);
)
$ row + +;
)
fclose ($ handle);
Else ()
echo "Connecting to the SQLite database:". $ DatabaseFile. "Failed";
)
Else ()
echo "
Usage:
tableFromCsv.php database tableName csvFilename [separator] [delimitor] ";
)

Add comment

Security code
Refresh

Create table from CSV - SQLiteManager
Facebook MySpace Twitter Digg Delicious Stumbleupon Google Bookmarks 

Author

SQLiteManager now is managed by the corporation WebInfoPro in order to remake to live this project all while remaining under license GPL

Contact

Vous pouvez nous contacter par email sur sqlitemanager@gmail.com

Who's online?

We have 38 guests online