python: update mysql table - python

I am trying to update a mysql table with variable names. Below is the code that is not working for me:
import mysql.connector
conn= mysql.connector.connect(
host=host,
user=user,
passwd=password,
database=database
)
cur = conn.cursor()
cur.execute("update player_list set country = '%s', region = '%s',name = '%s' where id = %s "
% (country, region,name, id))
Running the "cur execute" line returns the following error:
mysql.connector.errors.InternalError: Unread result found
The ID column is an integer if it has any importance.

I don't see any code here how you've created your cursor, but looks like you need to specify buffered mode for your sql class to read.
Please, refer to official documentation and change your code to use buffer=True while creating your cursor and use it afterwards.
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorbuffered.html

Try
with conn.cursor() as cur:
sql = "update player_list set country = '%s', region = '%s',name = '%s' where id = %s" % (country, region,name, id)
cur.execute(sql)
conn.commit()
and add buffered = True into your conn like
connection = mysql.connector.connect([...], buffered = True)

Related

I'm using python, and I work with SELECT and UPDATE statement in a single cursor for the same table

Here is the code that I try to run
connection = mysql.connector.connect(host='host',
database="database",
user="user",
password="password")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee WHERE admin = 'true'")
dict_result = cursor.fetchone()
while dict_result is not None:
print(dict_result)
cursor.execute("UPDATE employee SET salary = 10000 WHERE uuid = '%s'" % (dict_result[0]))
dict_result = cursor.fetchone()
connection.close()
Error achieved by above:
But i got 'unread result found' error
I had a similar error where i had to commit after the fetch to make sure that all of the results was gathered as the fetch call is asynchronous.
My fix was to add:
connection.commit()
After the fetch but before the close.
Ex:
connection = mysql.connector.connect(host='host',
database="database",
user="user",
password="password")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee WHERE admin = 'true'")
dict_result = cursor.fetchone()
while dict_result is not None:
print(dict_result)
cursor.execute("UPDATE employee SET salary = 10000 WHERE uuid = '%s'" % (dict_result[0]))
dict_result = cursor.fetchone()
connection.commit()
connection.close()

Mysql table name getting unwanted quotes resulting table does not exist error

import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")
I have the code above and giving me the below error:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist
aud-cad_30mins table does exist and an insert query like below doing its job:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )"""
So when I try to use variables in the query, it gives the error. Why the table name getting unwanted quotes? Checked several tutorials but couldn't find a solution, any ideas?
The table name should be hardcoded in the query string instead of having it there as a placeholder %s, which is meant for the values to be inserted. So if you have the table name in the variable, you can replace it via format() before calling cursor.execute()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)
see the examples in the docs
edit: as Bill mentioned in the comment, dont add the backticks around the %s placeholders.

Python MySQL Update Query

I am trying to update a SQL Table given a users input I have the following code. The user can choose to enter in/change the below fields which are defaulted to the values in the SQL table. However when I run the code I get the following error message
mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement
I have counted it many times and it seems like the %s match the passed parameters. Am I missing something?
user = User_name_body.get('1.0',END)
passw = Password_text.get('1.0',END)
first = First_name.get('1.0',END)
last = Last_name.get('1.0',END)
phone = Phone_number.get('1.0',END)
email = Email_address.get('1.0',END)
mycursor = mydb.cursor()
sql = "UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name=%s VALUES(%s,%s,%s,%s,%s,%s)"
val = (email, first, last, phone, passw,user)
mycursor.execute(sql, val)
mydb.commit()
mydb.close()
UPDATE does not take VALUES, you should change your sql query line to look like this:
sql = "UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name=%s"
Python throws an error because you are asking for 12 parameters and only providing 6.
Prepare your sql data like this:
sql = """ UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name = %s """
val = (email, first, last, phone, passw, user)
mycursor.execute(sql, val)
or you can do it like this
sql = "UPDATE btms_users SET btms_users.user='%s', btms_users.secret='%s' , btms_users.first_name='%s', " \
"btms_users.second_name='%s', btms_users.email='%s', btms_users.mobile='%s' " \
"WHERE btms_users.id='%s'" % (user_name, user_secret, user_firstname, user_lastname,
user_email, user_phone, user_id)
mycursor.execute(sql)
and here is a full working example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="test",
database="test"
)
mycursor = mydb.cursor()
sql = "UPDATE items SET name = %s WHERE id = %s"
val = ("Test", 1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

Inserting into a database table not working with Python

I am inserting into a table using the following code:
## Connection established ##
sql = """ INSERT INTO Singer ( name ) VALUES( %s ) """
params = ('Rihanna',)
cursor.execute(sql, params)
cursor.fetchall() ## Result - into no result set
cursor.description ## Result - Nonetype
I am not able to understand where am I going wrong?
Thanks
You have to commit your change.
cursor = conn.cursor()
sql = """ INSERT INTO Singer ( name ) VALUES( %s ) """
params = ('Rihanna',)
cursor.execute(sql, params)
conn.commit() # Important, apply changes to database!
cursor.fetchall() ## Result - into no result set
cursor.description ## Result - Nonetype

mysql table is not committed by commit() after delete row

I am trying to delete multiple rows in mysql table, through a loop in python. There is no error message but finally the table is not being updated. My code is:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="Share")
mycursor = mydb.cursor()
for i in range(288, 297):
sql = "DELETE from name_list where ID = " + str(i)
mycursor.execute(sql)
mydb.commit()
mycursor.execute("SELECT * from Share.name_list")
for row in mycursor.fetchall() :
print(row)
Thanks
How about this?
for i in range(288, 297):
sql = "DELETE from name_list where ID = %s"
mycursor.execute(sql, (i, ))
mydb.commit()
source
this should automatically quote the variable based on the datatype and has the added benefit of sql injection protection.
In this case it doesn't matter, since the parameter is always generated by range() but concatenating variables into sql queries manually is generally bad habit.

Categories

Resources