down below is my code to get some data from MySQL for my 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"))
The output of print(fetch("test")) always None and i dont know why.
I tried to check the database, and look into the code for 1 million times, but the database is working normal, and I dont know why
Any idea about this?
Thanks to yall help! I've seen Barmar comment:
Actually, I'm already have another function to check the table exists or not:
But I'm just realized, it doesn't fell good in this problem. I tried to update my
save()function:And it's likely to working now