无法从MySQL数据库获取数据

Cannot get data from MySQL database

提问人:tudubucket 提问时间:9/1/2023 更新时间:9/2/2023 访问量:47

问:

下面是我从 MySQL 为我的 Discord Bot 获取一些数据的代码:

import traceback
import mysql.connector


DB_CONFIG = {
    'host': 'mydomain',
    'port': 3306,
    'user': 'user',
    'password': 'pass',
    'database': 'dbname'
}

def fetch(table):
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        cursor.execute(f"SELECT json_data FROM {table} WHERE id = 1")
        result = cursor.fetchone()
        if result:
            return json.dumps(result[0])
        else:
            return {}

    except Exception as e:
        print(str(e))
        return {}

    finally:
        cursor.close()
        conn.close()

def save(data, table):
    try:
        json_data = json.dumps(str(data))
        print(json_data)
        check_table(table)
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        cursor.execute(f"UPDATE {table} SET json_data = %s WHERE id = 1", (json_data,))
        conn.commit()
        print(f"{table}'s table saved successfully.")
      
    except Exception as e:
        print(str(e))
        traceback.print_exc()

    finally:
        cursor.close()
        conn.close()


test = {"a": "b"}
save(test, "test")
print(fetch("test"))

总是 None 的输出,我不知道为什么。print(fetch("test"))

我试着检查数据库,查看代码100万次,但是数据库工作正常,不知道为什么

对此有任何想法吗?

mysql连接器-python

评论

0赞 Nuno Mariz 9/1/2023
很难知道它为什么返回,因为我们不知道数据。代码看起来不错。尝试通过打印 中的结果进行调试。Noneresult = cursor.fetchone()
0赞 Barmar 9/2/2023
没有办法可以返回。所有路径都返回空字典或 JSON 字符串。fetch("test")None
0赞 Barmar 9/2/2023
save()仅当表中已有一行 .如果该行不存在,则不会创建该行。为此,您应该使用id=1INSERT ... ON DUPLICATE KEY UPDATE ...
0赞 Barmar 9/2/2023
仅供参考,更新不存在的行不会导致错误。
0赞 Barmar 9/2/2023
json.dumps(result[0])应该是 .该表包含一个 JSON 对象,您希望在获取时将其解析为字典。json.loads(result[0])

答:

0赞 tudubucket 9/2/2023 #1

感谢你们的帮助!我看到 Barmar 评论道:

save() 仅在表中已经有一行 id=1 时才有效。如果该行不存在,则不会创建该行。

实际上,我已经有另一个函数来检查表是否存在:

def check_table(table):
    try:
        query = f"""CREATE TABLE IF NOT EXISTS {table} (
            id INT AUTO_INCREMENT PRIMARY KEY,
            json_data JSON
        );
        """
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        cursor.execute(f"SHOW TABLES LIKE '{table}'")
        table_exists = cursor.fetchone()
        if not table_exists:
            cursor.execute(query)
            print(f"Table '{table}' created successfully.")
        conn.commit()
    except Exception as e:
        print(str(e))
        traceback.print_exc()

    finally:
        cursor.close()
        conn.close()

但我刚刚意识到,这个问题并不好。我尝试更新我的函数:save()

...
        cursor = conn.cursor()
        # cursor.execute(f"UPDATE {table} SET json_data = %s WHERE id = 1", (json_data,))    Old code line
        # First, check if the record with id=1 exists
        cursor.execute(f"SELECT id FROM {table} WHERE id = 1")
        existing_record = cursor.fetchone()

        if existing_record:
            # If the record with id=1 exists, update it
            cursor.execute(
                f"UPDATE {table} SET json_data = %s WHERE id = 1",
                (json_data,)
            )
        else:
            # If the record with id=1 doesn't exist, insert it
            cursor.execute(
                f"INSERT INTO {table} (id, json_data) VALUES (1, %s)",
                (json_data,)
            )
...

它现在很可能会起作用image