| 1 |
======= |
| 2 |
sql2csv |
| 3 |
======= |
| 4 |
|
| 5 |
Description |
| 6 |
=========== |
| 7 |
|
| 8 |
Executes arbitrary commands against a SQL database and outputs the results as a CSV: |
| 9 |
|
| 10 |
.. code-block:: none |
| 11 |
|
| 12 |
usage: sql2csv [-h] [-v] [-l] [-V] [--db CONNECTION_STRING] [--query QUERY] |
| 13 |
[-e ENCODING] [-H] |
| 14 |
[FILE] |
| 15 |
|
| 16 |
Execute a SQL query on a database and output the result to a CSV file. |
| 17 |
|
| 18 |
positional arguments: |
| 19 |
FILE The file to use as the SQL query. If FILE and --query |
| 20 |
are omitted, the query is piped data via STDIN. |
| 21 |
|
| 22 |
optional arguments: |
| 23 |
-h, --help show this help message and exit |
| 24 |
--db CONNECTION_STRING |
| 25 |
A SQLAlchemy connection string to connect to a |
| 26 |
database. |
| 27 |
--engine-option ENGINE_OPTION ENGINE_OPTION |
| 28 |
A keyword argument to SQLAlchemy's create_engine(), as |
| 29 |
a space-separated pair. This option can be specified |
| 30 |
multiple times. For example: thick_mode True |
| 31 |
--execution-option EXECUTION_OPTION EXECUTION_OPTION |
| 32 |
A keyword argument to SQLAlchemy's |
| 33 |
execution_options(), as a space-separated pair. This |
| 34 |
option can be specified multiple times. For example: |
| 35 |
stream_results True |
| 36 |
--query QUERY The SQL query to execute. Overrides FILE and STDIN. |
| 37 |
-e ENCODING, --encoding ENCODING |
| 38 |
Specify the encoding of the input query file. |
| 39 |
-H, --no-header-row Do not output column names. |
| 40 |
|
| 41 |
Examples |
| 42 |
======== |
| 43 |
|
| 44 |
Load sample data into a table using :doc:`csvsql` and then query it using `sql2csv`: |
| 45 |
|
| 46 |
.. code-block:: bash |
| 47 |
|
| 48 |
csvsql --db "sqlite:///dummy.db" --tables "test" --insert examples/dummy.csv |
| 49 |
sql2csv --db "sqlite:///dummy.db" --query "select * from test" |
| 50 |
|
| 51 |
Load data about financial aid recipients into PostgreSQL. Then find the three states that received the most, while also filtering out empty rows: |
| 52 |
|
| 53 |
.. code-block:: bash |
| 54 |
|
| 55 |
createdb recipients |
| 56 |
csvsql --db "postgresql:///recipients" --tables "fy09" --insert examples/realdata/FY09_EDU_Recipients_by_State.csv |
| 57 |
sql2csv --db "postgresql:///recipients" --query "select * from fy09 where \"State Name\" != '' order by fy09.\"TOTAL\" limit 3" |
| 58 |
|
| 59 |
You can even use it as a simple SQL calculator (in this example an in-memory SQLite database is used as the default): |
| 60 |
|
| 61 |
.. code-block:: bash |
| 62 |
|
| 63 |
sql2csv --query "select 300 * 47 % 14 * 27 + 7000" |
| 64 |
|
| 65 |
The connection string `accepts parameters <https://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#engine-creation-api>`_. For example, to set the encoding of a MySQL database: |
| 66 |
|
| 67 |
.. code-block:: bash |
| 68 |
|
| 69 |
sql2csv --db 'mysql://user:pass@host/database?charset=utf8' --query "SELECT myfield FROM mytable" |