How do I create a CSV file from database in Python?

前端 未结 8 2021
南方客
南方客 2020-12-05 00:05

I have a Sqlite 3 and/or MySQL table named \"clients\"..

Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect...

8条回答
  •  春和景丽
    2020-12-05 00:45

    How to extract the column headings from an existing table:

    You don't need to parse an SQL "create table" statement. This is fortunate, as the "create table" syntax is neither nice nor clean, it is warthog-ugly.

    You can use the table_info pragma. It gives you useful information about each column in a table, including the name of the column.

    Example:

    >>> #coding: ascii
    ... import sqlite3
    >>>
    >>> def get_col_names(cursor, table_name):
    ...     results = cursor.execute("PRAGMA table_info(%s);" % table_name)
    ...     return [row[1] for row in results]
    ...
    >>> def wrong_way(cur, table):
    ...     import re
    ...     cur.execute("SELECT sql FROM sqlite_master WHERE name=?;", (table, ))
    ...     sql = cur.fetchone()[0]
    ...     column_defs = re.findall("[(](.*)[)]", sql)[0]
    ...     first_words = (line.split()[0].strip() for line in column_defs.split(','))
    ...     columns = [word for word in first_words if word.upper() != "CONSTRAINT"]
    ...     return columns
    ...
    >>> conn = sqlite3.connect(":memory:")
    >>> curs = conn.cursor()
    >>> _ignored = curs.execute(
    ...     "create table foo (id integer, name text, [haha gotcha] text);"
    ...     )
    >>> print get_col_names(curs, "foo")
    [u'id', u'name', u'haha gotcha']
    >>> print wrong_way(curs, "foo")
    [u'id', u'name', u'[haha'] <<<<<===== WHOOPS!
    >>>
    

    Other problems with the now-deleted "parse the create table SQL" answer:

    1. Stuffs up with e.g. create table test (id1 text, id2 int, msg text, primary key(id1, id2)) ... needs to ignore not only CONSTRAINT, but also keywords PRIMARY, UNIQUE, CHECK and FOREIGN (see the create table docs).

    2. Needs to specify re.DOTALL in case there are newlines in the SQL.

    3. In line.split()[0].strip() the strip is redundant.

提交回复
热议问题