这是我的代码:
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
最佳答案
看起来show_tables(self)正在返回null,一个关于None对象的列表,因为你只能调用一次cursor.fetchall()。
解决方案:注释该行
print(self.fetchall())
关于python - 在 Python 中从数据库元组中获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36873303/