I have a problem that my code did’t give me output, it’s connect Python to MySql without change the value I want to change, I have 2 scripts file one of them config have my host, password and user and another init
import mysql.connector
from config import USER, PASSWORD, HOST
class DbConnectionError(Exception):
pass
# make a conniction to DB
def _connect_to_db(db_name):
cnx = mysql.connector.connect(
host=HOST,
user=USER,
password=PASSWORD,
auth_plugin='mysql_native_password',
database=db_name
)
return cnx
def change_maximum_mark():
try:
db_name = 'tests'
db_connection = _connect_to_db(db_name)
cur = db_connection.cursor()
print(f'connected to database {db_name}')
query = """
UPDATE exams
SET Max_mark = 100
WHERE Exam_Name = 'Math'
"""
cur.execute(query)
result = cur.fetchall()
for i in result:
print(i)
cur.close()
except Exception:
raise DbConnectionError("Failed to read data from DB")
finally:
if db_connection:
db_connection.close()
print('DB conniction is closed')
I run these code to change value in mysql table, I success to connect Python and my sql but unfortunately the value not changed enter image description here
2
Answers
the code is right no problem with a code the problem is using safe update mode , that you must off it with this code.
You forgot to commit the query.
Add this piece of code:
Then, I have a question for you: a sql update query does not return any table, so, what are you printing?
I think you should execute a
SELECT
query after the update.