【问题标题】:Avoid None in cursor.description?在 cursor.description 中避免 None?
【发布时间】:2021-03-05 19:18:54
【问题描述】:

我在 Python 中使用 sqlite3。

我的桌子:

cursor.execute("""create table student(rno int, name char(20), grade char, gender char, avg decimal(5,2), dob date);""")

其中 cursor 是我的光标对象的名称 ...

我使用 cursor.description 来显示列名。但是每个元组中有七个字符串,其中六个是 None

print(cursor.description)
Output : (('rno', None, None, None, None, None, None), ('name', None, None, None, None, None, None), ('grade', None, None, None, None, None, None), ('gender', None, None, None, None, None, None), ('avg', None, None, None, None, None, None), ('dob', None, None, None, None, None, None))

API 可以看出,每个元组的前两个元素是必须的。但这不适合我。为什么?

我还应该在我的表中进行哪些更改以获取设置为无的其他元素的值???

感谢任何相关的帮助....

【问题讨论】:

  • 这 7 项中的哪一项对您很重要?您需要的不仅仅是列名和数据类型吗?

标签: python sqlite cursor


【解决方案1】:

DB API2.0 的 sqlite3 只保证第一项。

它为每一列返回一个 7 元组,其中每列的最后六项 元组是无。

https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.description

要打印所有详细信息,我猜你应该有一些数据。 可能是添加一些数据并执行选择语句

【讨论】:

  • 我正在处理 Python 中的 SQLite3,而不是 MySQL。请调整你的答案
  • 我只是把它作为一个例子来打印描述......对于python DB API 2.0......
  • 据我了解,问题是如何在 cursor.description 中获取更多信息。这个答案说:除了列名,您将不会获得更多信息。 lib SQLite3 没有提供更多。
【解决方案2】:

这是一种方法。仍在您的原始代码中使用cursor.description

  1. 创建一个函数来显示数据库中的所有记录
def show_all():
    # connect to db
    conn = sqlite3.connect('student.db')

    # create cursor
    c = conn.cursor()

    # query the db
    c.execute("SELECT rowid, * FROM student")

    items = c.fetchall()

    for item in items:
         print(item)
  1. 然后在关闭您正在使用的表/数据库的连接之前
    # column names
    col_desc = []
    columns = c.description
    for column in columns:
        col_desc.append(column[0])
    print(col_desc)
  1. 然后您可以在单独的文件中导入您正在使用的database 并执行函数
import student

students.show_all()

【讨论】:

  • 请再次阅读我的问题...我没有要求代码显示列名
【解决方案3】:

显然 type_code 在 sqllite 3 上被返回为 None 是一个错误,请参阅链接了解更多详细信息。

bug Details

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多