Failed to insert user input into MySQL database - python

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.

Related

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")

Unable to fetch results from SQL to Python using mysql.connector

I am trying to query a table stored in SQL using python. I am using mysql.connector package to perform the task.
import mysql.connector
#Creating a connection
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="something",
database='mydatabase',
)
print(mydb)
##Creating a table called customers
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
#Inserting records to the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345')]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
The problem is when I query the database, there is no output displayed.
query=("SELECT name, address FROM customers")
mycursor.execute(query)
for (name, address) in mycursor:
print("{} {}".format(name, address))
Here is a link to what I tried and where I got the code from.
Link:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
Here is the confirmation that the query is storing rows in the database.
The code is running fine. The issue seems to be in the line mycursor.executemany(sql, oval) as the variable is defined as val above. Fixing that should give you the expected output.

Python function to add a tuple to MySql not working

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

Python/MySQL - Error 1064, can't figure it out

I've been trying to find out what causes the error. I believe it is in the last query to the database. I've marked it with comments.
This error has been giving me a headache for the past 30 minutes.
import MySQLdb
import time
# Create a database connection
db = MySQLdb.connect(host="******", user="******", passwd="*****", db="*****")
cur = db.cursor()
# Create a query to select all IDs
cur.execute("SELECT id FROM users")
clientArray = []
# Loop over all IDs returned from query,
# save all IDs in the clientArray
for row in cur.fetchall():
clientID = str(row[0])
clientArray.append(clientID)
clientIDInput = ""
while True:
# Check and wait for input
clientIDInput = raw_input("")
if clientIDInput in clientArray:
# Check to see whether user is already signed in to the device
cur.execute("SELECT fitnessStatus FROM users WHERE id=%s", (clientIDInput))
data = cur.fetchone()
if data[0] == False:
cur.execute("UPDATE users SET fitnessStatus='1' WHERE id=%s", (clientIDInput))
checkInTime = time.strftime('%Y-%m-%d %H:%M:%S')
checkOutID = raw_input("")
if checkOutID == clientIDInput:
cur.execute("UPDATE users SET fitnessStatus='0' WHERE id=%s", (clientIDInput))
checkOutTime = time.strftime('%Y-%m-%d %H:%M:%S')
print checkInTime
print checkOutTime
### I BELIEVE THIS IS THE CAUSE OF THE ERROR ###
cur.execute("INSERT INTO activities (id, machinename, checkin, checkout, clientid) VALUES (NULL, Cross Trainer #5, %s, %s, %s)", (checkInTime, checkOutTime, clientIDInput))
# Send checkInTime and checkOutTime to database
There is a syntax error in your INSERT statement. Try to enclose the string 'Cross Trainer #5' in single quotes:
cur.execute("INSERT INTO activities (id, machinename, checkin, checkout, clientid) VALUES (NULL, 'Cross Trainer #5', %s, %s, %s)", (checkInTime, checkOutTime, clientIDInput))`
Luckily, the statement itself is already enclosed in double quotes " so that no further change would be required :)
The error 1064 is a bit misleading. It indicates, amongst others, abuse of a reserved word. And indeed: CROSS is a reserved word.

python dynamic input, update table

I wrote a program in order to dynamically update a database table but I am getting an error. I stuffed the program with whatever I know little about. Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter film: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()
This is the error:
File "C:\Python27\maybe1.py", line 20, in <module>
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
How can I fix this issue ?
You should change ? to %s.
Here is question about why mysqldb use %s instead of ?.
I would do it this way:
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
Replace %s with correct data type, else it will try everything as string which might break at table level.

Categories

Resources