簡體   English   中英

在函數之外訪問類

[英]Access a class outside the function

我想訪問mycursor( class中的數據類型) sql_process()函數,其在定義sql_connect功能。 代碼是:

def sql_connect():
    print("In sql_connect function")
    mydb = mysql.connector.connect(
        host="localhost",
        user="jarvis",
        passwd="raspberry",
        database="nGShelter"
        )
    mycursor = mydb.cursor() #type(mycursor) ---> class
    return(mycursor)

def sql_process():
    print("In sql_process function")
    try:
        sql_connect().execute("SHOW Tables")
        for tables in mycursor:
            print(tables)
    except mysql.connector.Error as err:
        print("Failed to open database: {}".format(err))
        exit(1)

def main():
    sql_connect()
    sql_process()
##    

if __name__ == '__main__':
    sys.exit(main())

運行時發生錯誤

In sql_connect function
In sql_process function
In sql_connect function
Traceback (most recent call last):
  File "/home/pi/Projects/json_mysql_post.py", line 42, in <module>
    sys.exit(main())
  File "/home/pi/Projects/json_mysql_post.py", line 38, in main
    sql_process()
  File "/home/pi/Projects/json_mysql_post.py", line 29, in sql_process
    sql_connect().execute("SHOW Tables")
  File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 526, in execute
    if not self._connection:
ReferenceError: weakly-referenced object no longer exists

不讓示波器消失的解決方法

class SQLOps:
    def __init__(self):
        print("In sql_connect function")
        self.mydb = mysql.connector.connect(
            host="localhost",
            user="jarvis",
            passwd="raspberry",
            database="nGShelter"
        )
        self.mycursor = self.mydb.cursor()
    def sql_process(self):
        print("In sql_process function")
        try:
            self.mycursor.execute("SHOW Tables")
            for tables in self.mycursor:
                print(tables)
        except mysql.connector.Error as err:
            print("Failed to open database: {}".format(err))
            exit(1)

def main():
    sql = SQLOps()
    sql.sql_process()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM