如何在python中从SQLite数据库打印表?

时间:2016-04-22 12:40:00

标签: python database sqlite printing

所以我有一个信息数据库,我希望以一种漂亮的表格格式打印,作为SQLite数据库文件保存。

我见过的唯一打印语句以混乱的方式打印信息,没有对齐不同实体的属性,没有列标题等。

创建表的过程:

def create_table():
c.execute('CREATE TABLE IF NOT EXISTS orders ( '    #CREATES TABLE named 'orders':
          'name TEXT, '                             #name
          'type_ TEXT, '                            #type of product
          'location STRING, '                       #location of product
          'amount INTEGER, '                        #'weight' of item, g, kg, ml, cl, l, etc. 
          'wholesale_cost REAL, '                   #wholesale cost
          'tax REAL, '                              #tax %
          'sale_pre_tax REAL, '                     #sale value before tax
          'sale_post_tax REAL, '                    #sale value after tax
          'quantity REAL, '                         #how many sold
          'total_sale_pre_tax REAL, '               #total sales before tax
          'total_sale_post_tax, '                   #total sales after tax
          'total_tax REAL, '                        #total tax in GBP
          'total_wholesale_cost REAL, '             #total wholesale cos
          'profit REAL)')                           #total sale profit

这是打印程序:

def read_from_db():
c.execute ('SELECT * FROM orders ') 
for row in c.fetchall():
    print(row)

执行此操作时,会打印:

  

(' NORI',' DRY',' SHELVES',' 50G',3.4,20.0,4.42,5.303999999999999,   3.0,13.26,15.911999999999999,2.65999999999999992,10.2,3.0000000000000000005)

     

(' CURRY SAUCE',' DRY',' SHELVES',' 500G',5.65,25.0,   7.345000000000001,9.18125,1.0,7.345000000000001,9.18125,1.8362499999999997,5.65,1.6950000000000003)

     

(' SALMON',' CHILLED',' FRIDGE',' 100G',1.25,20.0,1.625,1.95,10.0,   4.875,5.85,0.9749999999999996,3.75,1.125)

     

(' EDAMAME',' CHILLED',' FRIDGE',' 100G',3.0,19.0,4.0,5.0,3.0,   12.0,15,3.0,9.0,3.0)

我的数据库中有哪些信息,但有没有办法将其打印为表格?

1 个答案:

答案 0 :(得分:0)

使用row_factory向您的行添加列名是well documented

import sqlite3

con = sqlite3.Connection('my.db')
con.row_factory = sqlite3.Row

cur = con.cursor()
cur.execute('SELECT * FROM tbl')

for row in cur.fetchall():
     # can convert to dict if you want:
     print(dict(row))

然后,您可以使用str.rjust及相关功能打印表格,或使用csv.DictWriter sys.stdout作为“文件”:

import csv
import sys

wtr = csv.DictWriter(sys.stdout, fieldnames=[i[0] for i in cur.description])
wtr.writeheader()

for row in cur.fetchall():
    wtr.writerow(dict(row))