首页 > 解决方案 > 使用 MySQL 连接时的 Python OOP 编程问题

问题描述

我正在尝试编写一个将用于 IOS 应用程序的后端。我知道这在技术上是错误的,但它不会被部署。

我的问题是我收到错误

self.cursor(query)
TypeError: 'CMySQLCursor' object is not callable

当我运行以下命令时会发生这种情况main.py

import database


db = database.database()

staff = db.getData("SELECT * FROM timesheets.staff")

最后这是我的database.py代码

import mysql.connector

class database :
    conn = ""
    cursor = ""

    def __init__(self):
        self.conn = mysql.connector.connect(user='james',
                                       password='timeismoney',
                                       host='hallfamily.mycrestron.com',
                                       database='timesheets',
                                       port='6033')

        self.cursor = self.conn.cursor()

        print("Done")

    def getData(self, query):

        #Checking if the user has applied a string
        if isinstance(query, str):
            self.cursor(query)
        else:
            return "You have provided a request that cant be processed"

        #Fetching all the results
        result = self.cursor.fetchall()

        #Returning back to the user
        return result

    def postData(self):
        print("Coming soon")


    def close(self):
        self.conn.close()

标签: pythonpython-3.xmysql-pythonpython-3.8

解决方案


代替:

self.cursor(query)

尝试这个:

self.cursor.execute(query)

推荐阅读