【问题标题】:mysql python: AttributeError: 'str' object has no attribute 'cursor'mysql python:AttributeError:'str'对象没有属性'cursor'
【发布时间】:2021-09-23 23:41:14
【问题描述】:

我想调用一个执行游标,但运气不佳.. 有什么问题?

我认为问题在于我打电话给database.execute(sql, val) 的地方是错误的……

这是我的代码

class database():
def connect(self):
    self.connection = mysql.connect (
        host='localhost',
        user='root',
        password='12345678',
        database='datasheet'
    )
    self.cursor = self.connection.cursor()

def execute(self, sql):
    return self.cursor.execute(sql)

def commit(self):
    self.connection.commit()

def add_to_user(self):
    sql = 'INSERT INTO `user` (`name`, `time`, `system`, `ip`) VALUES (%s, %s, %s, %s)'
    val = (
        'sama',
        f'{getData().current_date()}'
        + ' - ' +
        f'{getData().current_time()}',
        f'{getData().current_os()}',
        f'{getData().current_ip()}'
    )
    database.execute(sql, val)
    database.commit


database().add_to_user()

和我的终端:

Traceback (most recent call last):
  File "d:\WorkOuts\Back-End\Python\AutoKey\a.py", line 65, in <module>
    database().add_to_user()
  File "d:\WorkOuts\Back-End\Python\AutoKey\a.py", line 61, in add_to_user
    database.execute(sql, val)
  File "d:\WorkOuts\Back-End\Python\AutoKey\a.py", line 39, in execute
    return self.cursor.execute(sql)
AttributeError: 'str' object has no attribute 'cursor'

【问题讨论】:

    标签: mysql-python


    【解决方案1】:

    请修正你的缩进,因为它目前不是有效的 python,缩进在 python 中很重要。我假设你所有的函数都是数据库类的一部分,最后一行不是类的一部分。

    这两行

    database.execute(sql, val)
    database.commit
    

    应该使用self 而不是databasedatabase.commit 也没有做任何事情 - 它引用了该函数,但由于缺少 () 而没有调用它。

    尝试将这两行替换为:

    self.execute(sql, val)
    self.commit()
    

    另外,execute 不接受 val 参数。它可能应该被定义为

    def execute(self, sql, vals):
        return self.cursor.execute(sql, vals)
    

    你还需要在add_to_user()之前调用connect()

    【讨论】:

    • 感谢您的回答,我按照您说的做了,但仍然出现此错误AttributeError: 'database' object has no attribute 'cursor'
    • 应该是self.executeself.commit(不是前面给出的sql.)。
    猜你喜欢
    • 2016-06-26
    • 2016-11-08
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多