Send a Wildcard Characters in python sql query through %s - python

Code looks like this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = """SELECT * FROM customers WHERE address LIKE '%way%'"""
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This will select all the records whose address contain care like "way".
How to insert the wildcard dynamically by using %s
Basically I want to know how to use %s instead of 'way' in python so that the code will be more flexible.

try like below
query ="SELECT * FROM customers WHERE\
address LIKE '%"+variable+"%'"

Try escaping the percentage by doubling them.
>>> res = """SELECT * FROM customers WHERE address LIKE '%%%s%%'""" % ('way')
>>> res
"SELECT * FROM customers WHERE address LIKE '%way%'"

Related

How to include a variable in mysql connectivity query?

my_connect = mysql.connector.connect(
host="localhost",
user="xyz",
passwd="xyz",
database="tracking"
)
my_conn = my_connect.cursor()
x = input("enter name")
query="SELECT * FROM trackingtable WHERE Customer_Name = \"x\"";
print(query)
my_conn.execute(query)
my_conn.close()
Query printed statement
How do i get the proper query using the input from user? I tried using placeholders but I couldn't get them to work
Try:
query = f"SELECT * FROM trackingtable WHERE Customer_Name = {x}"
It's an f-string in which you can plug in variables via {}.
If you need the "s inside the query:
query = f'SELECT * FROM trackingtable WHERE Customer_Name = "{x}"'
Do you need the ; at the end?

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.

select multiple columns using SQLite3 in Python

I have a list that contains the name of columns I want to retrieve from a table in the database.
My question is how to make the cursor select columns specified in the list. Do I have to convert nameList to a string variable before include it in the select statement? Thanks
nameList = ['A','B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select * from table
""")
As long as you can be sure your input is sanitized -- to avoid SQL injection attack -- you can do:
...
qry = "select {} from table;"
qry.format( ','.join(nameList) )
cursor.execute(qry)
If you're on a really old version of Python do instead:
...
qry = "select %s from table;"
qry % ','.join(nameList)
cursor.execute(qry)
nameList = ["'A(pct)'",'B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select {} from table
""".format(", ".join(nameList)))

MySQL query returns data (u'example',)

I'm using a mysql lib on python, and when I try to do this query:
SELECT product FROM database1.contacts WHERE contact="%s" % (contact)
I get this:
(u'example',)
But I expect this:
example
Here is my code:
import mysql.connector
db_user = "root"
db_passwd = ""
db_host = "localhost"
db_name = "database1"
connector = mysql.connector.connect(user=db_user, password=db_passwd, host=db_host, database=db_name,
buffered=True)
cursor = connector.cursor()
contact = "943832628"
get_product_sql = 'SELECT product FROM database1.contacts WHERE contact="%s"' % (contact)
cursor.execute(get_product_sql)
for product in cursor:
print product
You are printing the whole row; print just the first column:
for product in cursor:
print product[0]
or use tuple unpacking in the loop:
for product, in cursor:
print product

How can I format strings to query with mysqldb in Python?

How do I do this correctly:
I want to do a query like this:
query = """SELECT * FROM sometable
order by %s %s
limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()
All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.
So it ends up like:
ORDER BY 'somecol' 'DESC'
Which is wrong should be:
ORDER BY somecol DESC
Any help greatly appreciated!
paramstyle
Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.
%s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:
query = """SELECT * FROM sometable order by %s %s limit %%s, %%s;"""
query = query % ('somecol', 'DESC')
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (limit1, limit2) )
results = cur.fetchall()
DO NOT FORGET to filter first substitution to prevent SQL-injection possibilities
Not all parts of an SQL query can be parametrized. The DESC keyword for example is not
a parameter. Try
query = """SELECT * FROM sometable
order by %s """ + sortorder + """
limit %s, %s"""
cur.execute(query, (sortname, limit1, limit2) )
You could try this alternatively...
query = """SELECT * FROM sometable
order by {0} {1}
limit {2}, {3};"""
sortname = 'somecol'
sortorder = 'DESC'
limit1 = 'limit1'
limit2 = 'limit2'
print(query.format(sortname, sortorder, limit1, limit2))

Categories

Resources