【问题标题】:List the tables of the database [duplicate]列出数据库的表[重复]
【发布时间】:2013-08-03 14:32:47
【问题描述】:

我想列出一个 sqlite3 数据库的所有表,但它不起作用。假设在 ma 数据库中,我有以下表:foo1, foo2, foo3, ... 然后,使用此代码:

cur.execute("SELECT name FROM sqlite_master")
for table in cur:
     print("The table is", table[0])

我有这个输出:The table is foo1,而我想要这个:

The table is foo1
The table is foo2
The table is foo3
…

但如果我将代码修改为:

cur.execute("SELECT name FROM sqlite_master")
print(cur.fetchone())
for table in cur:
     print("The table is", table[0]

那么输出是:

(foo1,)
The table is foo2

那么我的代码有什么问题?

【问题讨论】:

  • 我不这么认为。我已经使用您提供的链接来制作我的代码,但它不起作用。
  • 也许按名字订购? SELECT name FTOM sqlite_master ORDER BY name
  • 对于第三方来说,从问题中编辑语法错误通常是一个坏主意,因为它们通常会提供错误的线索,所以我将其回滚。 @Shan-x 如果 FTOM 实际上不在您的代码中,我建议您编辑问题。如果这些是拼写错误,我建议您复制并粘贴您的代码,而不是重新输入。
  • 将光标当作迭代器应该可以正常工作,而且cur.fetchone() 似乎可以工作,那么您是否尝试过测试cur.fetchall()

标签: python sqlite


【解决方案1】:

您的第一种方法应该有效(假设FTOMFROM):

import sqlite3
connection = sqlite3.connect(':memory:')
cur = connection.cursor()
cur.execute('CREATE TABLE foo1 (bar INTEGER, baz TIMESTAMP)')
cur.execute('CREATE TABLE foo2 (bar INTEGER, baz TIMESTAMP)')
cur.execute('CREATE TABLE foo3 (bar INTEGER, baz TIMESTAMP)')
cur.execute(
    "SELECT name FROM sqlite_master")
for table in cur:
    print(table[0])

打印

foo1
foo2
foo3

注意,要排除索引,请务必在 SQL 查询中添加 WHERE type='table'

【讨论】:

  • 是的,但我不能cur.execute('CREATE TABLE foo1 (bar INTEGER, baz TIMESTAMP)') 因为我不知道表名。事实上,我不想print(table[0]),而是这样做:cur.execute('CREATE TABLE {} (bar INTEGER, baz TIMESTAMP)'.format(table[0])。无论如何,这不能正常工作,我也不知道为什么。
猜你喜欢
  • 2012-10-03
  • 2014-01-09
  • 2019-05-18
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 2018-06-05
  • 2017-03-12
  • 2012-08-21
相关资源
最近更新 更多