How to use an UPDATE SQL statement with user input from Python? - python

I'm new to Python and especially to SQL.
My goal is:
A user should enter which phone number he wants to change
Then the user should be able to enter the new phone number
This change should then be stored in my MySQL database
As I know the syntax for an update is like this:
sql = "UPDATE table SET fieldname = value" "WHERE fieldname = value"
But if I try to use the code with two variables from an input, it doesn't work:
input_change = input("Write the number to change: ")
input_new = input("Write the new number: ")
sql = "UPDATE table SET telefonnummer = ?" "WHERE telefonnummer = ?"
cursor.execute(sql, (input_change, input_new))
connection.commit()
Does somebody have an idea how I can fix this? Or where can I find a good description about using variables in SQL statements?
Many thanks for the answers.

Change :
sql = "UPDATE table SET telefonnummer = ?" "WHERE telefonnummer = ?"
to
sql = "UPDATE table SET telefonnummer = ? WHERE telefonnummer = ?"
and
cursor.execute(sql, (input_change, input_new))
to
cursor.execute(sql, [input_change, input_new])

Related

Inserting data via Python into an SQLite table

I'm trying to solve this exercise, and I have no clue why my SQLite DB won't update. Here is what I tried. Any ideas would be much appreciated:
Also, I forgot how to keep the program running, I mean to keep showing the user the options he has :(
import sqlite3
conn = sqlite3.connect("Books")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Books(
id INT PRIMARY KEY,
title TEXT,
year INT);
""")
user_input = input ("Dear User, you have the following two options, two and only two (case sensitive): \n\t 1. INSERT \n\t 2. SHOW BOOKS \nPlease insert your comamnd here: <<< ")
if user_input == "1. INSERT":
book_id = input("Book id: ")
book_title = input("Book title: ")
book_year = input ("Book year of publication: ")
cursor.execute
(""" INSERT INTO Books (id, title, year) VALUES (?,?,?)
""", (book_id, book_title, book_year))
conn.commit()
print("Book inserted succesfully!")
elif user_input == "2. SHOW BOOKS":
cursor.execute("SELECT * FROM Books;")
all_results = cursor.fetchall()
print(all_results)
else:
print("Not a valid command. Try again! It's all case sensitive in Python, u know...")
if (conn):
conn.close()

Update multiple columns: the Username disappears

I am trying to update my user detail with Python and SQLite.
The aim is to upgrade all the columns of my user in one go.
My code is:
def update():
new_username = input("Input your NEW username:\n")
new_firstname = input("Input your NEW firstname:\n")
new_lastname = input("Input your NEW lastname:\n")
new_email = input("Input your NEW email:\n")
new_password = input("Input your NEW password:\n")
update_customer =("""UPDATE customer SET username = ? AND firstname = ? AND lastname = ? AND email = ? AND password = ?""")
cursor.execute(update_customer, [(new_username), (new_firstname), (new_lastname), (new_email), (new_password)])
I inspected the database before and after running my python function. However, the changes are not saved into the database. Nothing changes but the username that disappears.
You don't use AND for additional columns to be SET. Instead you separate the columns to be SET with a comma.
So you want
update_customer =("""UPDATE customer SET username = ?, firstname = ?, lastname = ?, email = ?, password = ?""")
and then a WHERE clause if not setting all rows to the same values.
As per :-
SQL As Understood By SQLite - UPDATE
You need to save changes after you completed the transaction.
cursor = conn.cursor() # Get cursor
cursor.execute(...) # Execute some SQL queries
# This is the line you've missed.
# You need to call this function every time you update the data in database.
cursor.commit()
Also, your SQL syntax for the "UPDATE" command is not correct. Use commas instead of "AND" when specifying multiple columns to be changed. Like this:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

use row as variable with python and sql

I am trying to update some values into a database. The user can give the row that should be changed. The input from the user, however is a string. When I try to parse this into the MySQL connector with python it gives an error because of the apostrophes. The code I have so far is:
import mysql.connector
conn = mysql.connector
conn = connector.connect(user=dbUser, password=dbPasswd, host=dbHost, database=dbName)
cursor = conn.cursor()
cursor.execute("""UPDATE Search SET %s = %s WHERE searchID = %s""", ('maxPrice', 300, 10,))
I get this error
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maxPrice' = 300 WHERE searchID = 10' at line 1
How do I get rid of the apostrophes? Because I think they are causing problems.
As noted, you can't prepare it using a field.
Perhaps the safest way is to allow only those fields that are expected, e.g.
#!/usr/bin/python
import os
import mysql.connector
conn = mysql.connector.connect(user=os.environ.get('USER'),
host='localhost',
database='sandbox',
unix_socket='/var/run/mysqld/mysqld.sock')
cur = conn.cursor(dictionary=True)
query = """SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'Search'
"""
cur.execute(query)
fields = [x['column_name'] for x in cur.fetchall()]
user_input = ['maxPrice', 300, 10]
if user_input[0] in fields:
cur.execute("""UPDATE Search SET {0} = {1} WHERE id = {1}""".format(user_input[0], '%s'),
tuple(user_input[1:]))
print cur.statement
Prints:
UPDATE Search SET maxPrice = 300 WHERE id = 10
Where:
mysql> show create table Search\G
*************************** 1. row ***************************
Search
CREATE TABLE `Search` (
`id` int(11) DEFAULT NULL,
`maxPrice` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
A column name is not a parameter. Put the column name maxPrice directly into your SQL.
cursor.execute("""UPDATE Search SET maxPrice = %s WHERE searchID = %s""", (300, 10))
If you want to use the same code with different column names, you would have to modify the string itself.
sql = "UPDATE Search SET {} = %s WHERE searchID = %s".format('maxPrice')
cursor.execute(sql, (300,10))
But bear in mind that this is not safe from injection the way parameters are, so make sure your column name is not a user-input string or anything like that.
You cannot do it like that. You need to place the column name in the string before you call cursor.execute. Column names cannot be used when transforming variables in cursor.execute.
Something like this would work:
sql = "UPDATE Search SET {} = %s WHERE searchID = %s".format('maxPrice')
cursor.execute(sql, (300, 10,))
You cannot dynamically bind object (e.g., column) names, only values. If that's the logic you're trying to achieve, you'd have to resort to string manipulation/formatting (with all the risks of SQL-injection attacks that come with it). E.g.:
sql = """UPDATE Search SET {} = %s WHERE searchID = %s""".format('maxPrice')
cursor.execute(sql, (300, 10,))

Displaying results from an Oracle query based on user input

I am trying to query the records for a specific ID in an Oracle table based on what the user inputs.
Here is my code:
import cx_Oracle
con = cx_Oracle.connect('dbuser/dbpassword#oracle_host/service_ID')
cur = con.cursor()
id_number = raw_input('What is the ID Number?')
cur.execute('select id, info from oracle_table_name where id=:id_number')
for result in cur:
print "test", result
cur.close()
con.close()
The following error pops up: cx_Oracle.DatabaseError: ORA-01008: not all variables bound
When I remove the user input and the variable substitution and run the query, everything works fine.
:id_number in your SQL is a parameter (variable). You need to provide its value.
execute method accepts parameters as the second argument.
Example:
query = "select * from some_table where col=:my_param"
cursor.execute(query, {'my_param': 5})
Check the documentation at http://cx-oracle.readthedocs.org/en/latest/cursor.html#Cursor.execute
I assigned a name to the user_value:
user_value = raw_input('What is the ID Number?')
And then referenced it in the execute statement:
cur.execute(query, {'id': (user_value)})
Thanks to Radoslaw-Roszkowiak for the assist!!

Use Python variable in a MySQL Subquery

team = input("Enter the team name: ")
cursor = db.cursor()
sql = "SELECT * FROM `flash_data_archive` WHERE `event_id` IN (SELECT `alternate_id` from `event_list` where `category` = %s)" % team
cursor.execute(sql)
What is the correct notation to have the the string the user entered for 'team' to be used for the category field in the sql subsuery?
Remove the % team from the string. Instead, it should be an argument to .execute.
cursor.execute(sql, team)
This will properly escape it.

Categories

Resources