Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import CSV file using PowerShell?

I want to import a CSV File (comma delimited with double quote) into SQLite using PowerShell script. I tried:

echo ".import export.csv mytable" | sqlite3.exe

I get this error:

export.csv:327: unescaped " character

I get this error for all lines. On SQLite's command line shell same command works:

sqlite > .import export.csv mytable

How can I make this command work using a PowerShell script?

like image 928
HBasiri Avatar asked May 22 '26 21:05

HBasiri


2 Answers

This works for me in both PowerShell 5.1 and v7.0.

$params = @"
.mode csv
.separator ,
.import export.csv mytable
"@

$params | .\sqlite3.exe mydatabase.db
like image 53
d3Xt3r Avatar answered May 25 '26 10:05

d3Xt3r


The following single command line works in both

  • cmd.exe (version 10.0.x.x via ver) and
  • powershell.exe (version 5.1.x.x via $PSVersionTable)
.\sqlite3.exe my.db ".import file1.csv table1 --csv"

This loads the contents of csv file file1.csv into table table1 within the sqlite database file my.db. The --csv flag will import the file and create the table structure based on the header column names in that file, and will approximately infer the data types.

You can import multiple files this way. i.e.

.\sqlite3.exe my.db ".import file1.csv table1 --csv" ".import file2.csv table2 --csv"

You can chain commands together to immediately open the database for querying by appending ; .\sqlite3.exe my.db.

i.e.

.\sqlite3.exe my.db ".import file1.csv table1 --csv" ".import file2.csv table2 --csv; .\sqlite3.exe my.db"
like image 43
qyb2zm302 Avatar answered May 25 '26 11:05

qyb2zm302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!