使用Python查询sql数据库中的所有表

时间:2018-03-17 09:29:22

标签: sql python-3.x sqlite

我正在使用python和sqlite3,我在读取自己创建的数据库中的表时遇到问题。

使用以下代码段

创建数据库
con = sqlite3.connect(folderdir + dbFileName)
#Create a cursor
c = con.cursor()
#Below code creates the data base. I later need to extract all tablename in 
my data base
c.execute('CREATE TABLE IF NOT EXISTS ' + tablename + ' (Bord text, Date 
    text, Time text, ID integer, Menu text, Qty integer, Price real, 
    Time_kitchen text, TableActive integer)')

c.execute('INSERT INTO ' + tablename + ''' (Bord, Date, Time, TableActive) 
    VALUES(?,?,?,?)''',
    (tablename, date, tabletime, 1))
con.commit()
con.close()

如果使用不同的tablename变量多次调用上面的代码,我会得到一个包含许多表名的database.db文件。我的问题是,即使使用sqlite_master,我也无法读出所有的表名。我使用下面的代码来读出

import sqlite3
#I have verified that I can connect successfully to the database file
con = sqlite3.connect(dbFilePath + "/" + dbFileName + ".db")
c = con.cursor()
c.execute("SELECT ALL Name FROM sqlite_master")
rows = c.fetchall()
for row in rows:
    print(row)

虽然我确实知道我有一个包含多个表名的数据库,但是打印没有返回任何内容。我做错了什么?

1 个答案:

答案 0 :(得分:0)

当名称赋予connect()的文件不存在时,SQLite会很乐意为您创建一个新的空数据库。

确保文件名正确无误;并且它不应该是相对文件名,以避免依赖于当前目录。