sql2csv
sql2csv OPTIONS SQL_STATEMENT
sql2csv OPTIONS CONFIG_FILE SQL_STATEMENT
sql2csv takes a config file describing a SQL database connection and output options needed and a SQL statement as the final parameter. The output of the SQL query is rendered in CSV format to standard out. sql2csv supports querying MySQL 8, Postgres and SQLite3 databases.
The configuration file is a JSON document with the following key value pairs.
To connect with a database sql2csv relies on a data source name (DSN) in URL format. In the URL form the URL’s scheme indicates the type of database you are connecting to (e.g. sqlite, mysql, postgres). The rest of the DNS has the following form
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
For a simple database like SQLite3 a minimal DSN in url form for a database file “my_database.sqlite3” would look like
sqlite://file:my_database.sqlite3
For MySQL you need to provide more information to connect (e.g. username, password). In this example the username is “jane.doe”, password is “something_secret” the database is “my_database”. (this example assumes that MySQL 8 is running on localhost at the usual port).
mysql://jane.doe:something_secret@/my_database
Postgres is similar to the MySQL connection string except the “scheme” is “postgres” instead of “mysql”.
A the following options will override a configuration.
Using the “dbcfg.json” configuration file, display ten rows from table “mytable” in database indicated in “dbcfg.json”.
'SELECT * FROM mytable LIMIT 10' sql2csv dbcfg.json
The CSV output is written standard out and can be redirected into a file if desired.
sql2csv dbcfg.json 'SELECT * FROM mytable LIMIT 10' \
>ten-rows.csv
Read SQL from a file and connect to Postgres without SSL you can pass
the -sql
and -dsn
options.
sql2csv \
-dsn "postgres://${USER}@/${DB_NAME}?sslmode=disable" \
-sql query.sql \
>my_data.csv