Using %s properly (Python) - python

import pymysql
conn = pymysql.connect('localhost','root','12345','cba')
myCursor = conn.cursor()
tn = str(input("Enter table name : "))
myCursor.execute("""CREATE TABLE %s (rollno int primary key auto_increment,name varchar(20),age varchar(50))"""%(tn,))
name = str(input("Enter name :"))
age = str(input("Enter age :"))
myCursor.execute("""insert into %s (name,age) values(%s,%s) """%(tn,)),(name , age)
print("Table name %s created"%(tn,))
i am getting error in line
myCursor.execute("""insert into %s (name,age) values(%s,%s)"""%(tn,name,age))
i tried
myCursor.execute("""insert into %s (name,age) values(%s,%s) """%(tn,)),(name,age)
please help me i am stil learning

You're mixing python's formatting method and pymsql's statement formatting. execute accepts args tuple for input values.
execute method doesn't allow inserting table's name. As as I understand documentation It has no any method for such operation http://pymysql.readthedocs.io/en/latest/user/index.html
So, you may use
sql = """insert into `{}` (name,age) values(%s,%s) """.format(tn)
myCursor.execute(sql ,(name , age))
Edit
But, this code is not perfect in the light of security. The first statement accepts any bad table name and inserts into sql statement. Please read about SQL injection. You should do some user input sanitation before inserting values into SQL statements directly.
execute statement should be OK as long as it takes care of escaping values.

Related

Trying to update the mysql table with user friendly input using string formatting

Though it is a repeated question , but want to know where my code is wrong as I am facing a syntax error .
def update_block():
table_name = input("Enter the name of the table: ")
column_update = input("Enter the column name to be updated: ")
column_name = input("Enter the column where the operation is to be performed: ")
name = input("Enter the name has to get update: ")
column_value = input("Enter the column value: ")
try:
sql_update_query = f"""Update {table_name} set {column_update} = %s where {column_name} = %s"""
inputData = (f"{name},{column_value}" )
my_cursor.execute(sql_update_query,inputData)
mydb.commit()
print("Record Updated successfully ")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
finally:
if (mydb.is_connected()):
my_cursor.close()
mydb.close()
print("MySQL connection is closed")
update_block()
error i am getting as :
Failed to update record to database: 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 '%s where prj_id = %s' at line 1
MySQL connection is closed
f"""Update {table_name} set {column_update} = %s where {column_name} = %s"""
You used f strings with curly brackets and %s notation here. Do either one and it should work
e.g.:
f"""Update {table_name} set {column_update} = {name} where {column_name} = {column_value}"""
There are two problems with the code.
In this line,
sql_update_query = f"""Update {table_name} set {column_update} = %s where {column_name} = %s"""
the table and column names should be quoted with backticks ("`") to handle names containing spaces or hyphens (or some unicode characters). So the line would look like this.
sql_update_query = f"""Update `{table_name}` set `{column_update}` = %s where `{column_name}` = %s"""
Note that the placeholders for variables should remain as %s.
In this line
inputData = (f"{name},{column_value}" )
the variables' values are being converted to strings within a single string. But the statement expects two variables, not one. Also, it is better* to pass the raw variables to the database connection and let the connection manage formatting them correctly in the final query. So the line should be
inputData = (name, column_value)
And now the statement can be executed with the related variables
my_cursor.execute(sql_update_query, inputData)
* The driver knows how to correctly convert Python data types into those expected by the database, and how to escape and quote these values. This provides at least two benefits:
it helps prevent SQL injection attacks, where a malicious user provides an SQL statement as a variable value (such as "; DELETE FROM mytable;"
it ensures that values are processed as expected; consider this statement:
SELECT '2020-09-01' AS `Quoted Date`, 2020-09-01 AS `Unquoted Date`;
+-------------+---------------+
| Quoted Date | Unquoted Date |
+-------------+---------------+
| 2020-09-01 | 2010 |
+-------------+---------------+

Facing issue in writing Nested Dictionaries to Newly Created SQL Table

I need to write the nested dictionaries in the newly created SQL Table.
I think I have made some mistake in creating new table in SQL by mentioning its column also. Could anyone please review the code & tell me whether this step is correct or not.
db = conn.connect(
host ="Localhost",
user ="root",
passwd ="admin",
database = "EMPLOYEE_DETAILS_00"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Details ( User_ID VARCHAR(255), Name VARCHAR(255), Age VARCHAR(255) ) ")
I need to write a nested Python dictionary into a SQL table. I'm trying to do it by using a for loop.
This is the code I'm trying to run:
user_details = {}
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
for v in user_details.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Details ({}) VALUES ({})".format(
', '.join(cols),
', '.join(['%s'] * len(cols)));
cursor.execute(sql, vals)
If I run this code I'm getting the following error
Error : Couldn't process parameters
Could anyone please review the code and tell me where I've made the mistake, whether in creating SQL Table or in FOR Loop.
Thanks in advance !!
I think issue is when you try to create sql query inside the loop.try this one
sql = "INSERT INTO Details {}) VALUES ({})".format(
', '.join(cols),
', '.join(map(str,vals)));

Write nested Python dictionary into SQL table

I think I have made some mistake in creating new table in SQL by mentioning its column also. Could anyone please review the code let me know your thoughts on this
db = conn.connect(
host ="Localhost",
user ="root",
passwd ="admin",
database = "EMPLOYEE_DETAILS_00"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Details ( User_ID VARCHAR(255), Name VARCHAR(255), Age VARCHAR(255), Occupation VARCHAR(255), Department VARCHAR(255), Salary VARCHAR(255), Address VARCHAR(255) ) ")
I need to write a nested Python dictionary into a SQL table. I'm trying to do it by using a for loop but I'm getting the following error:
Error : Couldn't process parameters
Can anyone provide me with any suggestions on this?
This is the code I'm trying to run:
user_details = {}
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
for v in user_details.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Details ({}) VALUES ({})".format(
', '.join(cols),
', '.join(['%s'] * len(cols)));
cursor.execute(sql, vals)
I would say your problem is at the last line, when you try to do cursor.execute(sql,(val,)).
In Python 3 dict.keys() and dict.values() doesn't return lists, but some dictionary view objects wrapping the data, so what you're getting from (val,) is a single value tuple with one dict_values object.
Try using just val as #niteshbisht suggested or list(val) or tuple(val) if that still doesn't work.
Please see also Python nested dictionary with SQL insert, as it looks like you're trying to address the same problem.
DON'T use the most obvious one (%s with %) in real code, it's open to attacks.
sql = ("INSERT INTO Details ? Values ?" ,(col, placeholders))
cursor.execute(sql,val)

How do I format an SQL where clause parameter in python with single quotes?

My Python code uses pyodbc to connect to a database and then asks the user for input which I would like to format the 'where' clause in an SQL statement but the where clause requires single quotation marks on my user input to function.
Every time I have tried to format the input to include single quotation mark it doesn't seem work and returns back no rows.
Here is what I am trying to achieve
"select FirstName, LastName from person.person where FirstName = 'Kim'"
where 'Kim' should be the user input.
here in my code section.
user_first_name = print(input("Enter the first name you are looking
for: "))
cursor.execute("select FirstName, LastName from person.person where
FirstName = ?", (user_first_name))
how do I format the input (user_first_name) so that the parameter has the single quotes in the query field.
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-3NLISNE\SQLNEW;DATABASE=TestDB;UID=python;PWD=password')
cursor = cnxn.cursor()
user_first_name = print(input("Enter the first name you are looking for:"))
query = "select FirstName, LastName from person.person where FirstName = ?"
result = cursor.execute(query, (user_first_name,))
rows = result.fetchall()
print (rows)

Parameterized Table Population

I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:
table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)
I get the following error:
TypeError: not enough arguments for format string
Thanks to anyone who takes the time to help. Have a great rest of the day :)
as an alternative you good go with the new formatting format
sql = f"INSERT INTO {tab} (name) VALUES ({val})".format(tab=db.escape_string(table_name),
val=value_name)
or
sql = f"INSERT INTO {db.escape_string(table_name)} (name) VALUES ({value_name})"
Just wrap the sql formatting like below and try.
sql = "INSERT INTO %s (name) VALUES (%s)" % (db.escape_string(table_name), value_name)

Categories