【发布时间】: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