Python Forum

Full Version: Format SQL Query Output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm selecting data from a table and returning all records. However, the records are being returned with a blank space separator instead of a comma. Any idea how to return rows like the following:

Output:
1,sales,marketing,04212020
Instead of:

Output:
1 sales marketing 04212020
Here's the function:

def select_from_database(conn, tablename):
    cursor = conn.cursor()
    print("Connected to: %s" % database)

    cursor.execute("SELECT * FROM %s " % tablename)
    rows = cursor.fetchall()
    print("Total records: %s" % len(rows))

    for i in rows:
        print(*i)
        #print("%s %s" % (row[0], row[1]))

    cursor.close()
Thanks!
I'd like to suggest sqlalchemy as a great alternative.
It does a lot of background tasks for you automatically.
Basics are simple to learn.
I have a tutorial on this forum here: https://python-forum.io/Thread-SqlAlchem...-Data-Load.
In a nutshell, you build a model which includes a class for each table, and import that model whenever a project needs access to your database.
Whenever you make an update (like adding a new column), the model will create the column for you (if you wish) and every module where that table is used will immediately have access (through the model) to the new data in that column.
rows is list of tuples. By print(*i) you just unpack each tuple into print and the default separator is space.
The simplest solutions is to specify sep argument to print function
print(*i, sep=',')
There are other options like using str.join() or string formatting. These would be helpful if you want to construct a string and assign it to a name.