[英]Mysql.connector in Python TypeError
我定义了一个数据库类,如下所示:
class Database(object):
""" Implements all interactions with the DB. """
def __init__(self, id_a, id_b, config):
self.config = config
self.id_a = id_a
self.id_b = id_b
self.db_connection = None
self.cursor = None
self.__init_db(config)
def __init_db(self, config):
"""
Initializes the MySQL Connector using the settings
specified in the system configuration.
"""
self.db_connection = mysql.connector.connect(user=config['database_user'],
password=config['database_password'],
host=config['database_host'],
database=config['database_name'])
self.cursor = self.db_connection.cursor(dictionary=True,buffered=True)
self.cursor.execute('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;')
现在,当我定义以下函数以返回从Mysql数据库获取的值时,出现错误
def get_func(self):
sql = "SELECT c_id FROM table \
WHERE id_a = {} ".format(self.id_a)
self.cursor.execute(sql)
rows = self.cursor.fetchone()
if rows:
for row in rows:
ls1 = row['id_number']
return ls1
ls1 = row['id_number']
TypeError: string indices must be integers
在row['id_number']
row
不是dict
类型的,而是tuple
类型的。
for row in rows:
ls1 = row['id_number'] # error
在你的情况下,你这样做
words = ('foo',)
words['id_number'] # error we need to pass only `int`
words[0] # right
# Output
# foo
而且该row
是单行,您无需将其for loop statment
仅需row[0]
row = self.cursor.fetchone()
if row:
return row[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.