【问题标题】:Get items from a database tuple in Python从 Python 中的数据库元组中获取项目
【发布时间】:2016-08-20 18:37:33
【问题描述】:

这是我的代码:

import pymysql

def connect():
    print("connect to database")
    pw = input("Password: ")
    conn = pymysql.connect(host='localhost', port=3306, 
                           user='root', passwd=pw, db='contacts')
    conn.autocommit(True)
    cur_ = conn.cursor()
    return cur_

def show_tables(self):
    print("show tables: ")
    self.execute("""SHOW TABLES""")
    print(self.fetchall())
    return self.fetchall()

db = connect()
table_names = show_tables(db)  # returns a tuple
print(len(table_names))  # output zero
table_name = table_names[0][0]  # ? - todo - get item from tuple

show_tables() 返回值(('person',),)。 我想用table_names[0][0] 获得名称person。但这不起作用。 (('person',),) 的长度也是 0。但是为什么呢?

编辑: 我得到了错误:

Traceback (most recent call last):
  File "/home/kame/Dropbox/code/python/scripts/database.py", line 65, in <module>
    table_name = table_names[0][0]  # ? - todo - get item from tuple
IndexError: tuple index out of range

【问题讨论】:

  • 你说“这行不通”。实际发生了什么?
  • this answer 有帮助吗?
  • 如果我先做p = (('person',),) 然后len(p),我会得到1 的预期。 p[0][0] 也给出了'person'(再次,正如预期的那样)。您确定要返回您认为要返回的元组吗?
  • 我会发布整个代码!
  • 向我们展示实际的 table_names 是什么,而不是您认为的应该是什么。

标签: python mysql database tuples pymysql


【解决方案1】:

看起来 show_tables(self) 正在返回 null,这是一个关于 None 对象的列表,因为您只能调用一次 cursor.fetchall()。

解决方案:注释行

print(self.fetchall())

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多