I'm trying to add an entry into mysql database from python. I don't get any errors when the code is executed, but the entry just doesn't appear in the database. Not sure where i'm going wrong. The columns in my cities table in mysql are city, state
mydb = mysql.connector.connect(**config)
mycursor = mydb.cursor()
print('type city')
city = input()
print('type state')
state = input()
insert = "insert into cities values('{0}', '{1}')".format(city, state)
mycursor.execute(insert)
mycursor.close()
Remember to commit mydb.commit() and it should work.
#danblack fixed sql injection
mydb = mysql.connector.connect(**config)
mycursor = mydb.cursor()
print('type city')
city = input()
print('type state')
state = input()
stmt = "INSERT INTO cities VALUES('%s', '%s');"
cursor.execute(stmt, (city, state))
mycursor.execute(insert)
mydb.commit()
Cheers
Related
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()
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")
I have created a database and inserted some value using python manual code but when i tried to taking input from user then inserting that input to my database table,i failed as i tried many ways.
Here is my code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Adee11ruchi#",
database="hdatabase"
)
mycursor = mydb.cursor()
name= str(input("What is your first name? "))
address=str(input("enter address:"))
#mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute = ("""INSERT INTO customers (name, address) VALUES (r{}, r{})""".format(name, address))
#val = ('Peter', 'Lowstreet 4')
mydb.commit()
print(mycursor.rowcount, "record inserted.")
It showing me as
What is your first name? diyu
enter address:hiouy
-1 record inserted.
What is the issue,i failed to find out.
You should be using a prepared statement here. Consider this version:
mycursor = mydb.cursor(prepared=True)
name = input("What is your first name? ")
address = input("enter address:")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
mycursor.execute = (sql, (name, address,))
mydb.commit()
The main takeaways points here are that you leave the values to be bound as parameters %s, and then you bind the values as a tuple in the call to cursor#execute. Note that the prepared statement API will handle the proper formatting of the inputs for you.
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.
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)