SQLalchemy-如何从sqlite文件提取表?

时间:2018-07-07 02:42:58

标签: python sqlalchemy

我想从sqlite文件中提取表信息。
我可以在此page之后列出所有表名,并尝试使用会话实例上的查询方法提取表信息。但我得到以下错误。

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: ComponentSizes [SQL: 'SELECT ComponentSizes']  

有人知道我应该如何修改以下代码以提取指定表名的表?

class read():
    def __init__(self,path):
        engine = create_engine("sqlite:///" + sqlFile)
        inspector=inspect(engine)
        for table_name in inspector.get_table_names():
            for column in inspector.get_columns(table_name):
                #print("Column: %s" % column['name'])
                print (table_name+" : "+column['name'])

        Session = sessionmaker(bind=engine)
        self.session = Session()

    def getTable(self,name):
        table=self.session.query(name).all()
        return table


if __name__ == '__main__':

    test=read(sqlFile)
    test.getTable('ComponentSizes')

1 个答案:

答案 0 :(得分:1)

您遇到的错误表明存在问题。您的代码正在翻译成SQL-SELECT ComponentSizes,但不完整。目前尚不清楚您的最终目标是什么。如果要将表的内容提取到CSV中,可以执行以下操作:

import sqlite3
import csv

con = sqlite3.connect('mydatabase.db')
outfile = open('mydump.csv', 'wb')
outcsv = csv.writer(outfile)

cursor = con.execute('select * from ComponentSizes')

# dump column titles (optional)
outcsv.writerow(x[0] for x in cursor.description)
# dump rows
outcsv.writerows(cursor.fetchall())

outfile.close()

否则,如果要将表的内容放入pandas df中以进行进一步分析,则可以选择执行以下操作:

import sqlite3
import pandas as pd
# Create your connection.
cnx = sqlite3.connect('file.db')

df = pd.read_sql_query("SELECT * FROM ComponentSizes", cnx)

希望有帮助。编码愉快!