Im not sure exactly whats happening here but it might have something to do with format in python.
Running this causes an error.
x = '00000201000012EB'
sql = """ SELECT * FROM table WHERE id = {} """.format(x)
conn.execute(sql)
I get an error saying: syntax error near "EB"
however when i run the command like this:
sql = """ SELECT * FROM table WHERE id = '00000201000012EB' """
conn.execute(sql)
It works fine.
Is there something wrong with the way im formatting this sql statement?
Use the variable as an argument to execute():
cur.execute(""" SELECT * FROM my_table WHERE id = %s """, (x,))
If you are determined to use format(), you should add single quotes around the placeholder:
sql = """ SELECT * FROM my_table WHERE id = '{}' """.format(x)
Believe it or not it was fixed by adding more quotes to the string.
this finally worked.
x = '00000201000012EB'
sql = """ SELECT * FROM table WHERE id = {} """.format("'" + x + "'")
Since the sql statement required another set of quotes i just added them to ensure it was treated as its own string.
Related
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 1 year ago.
nameEnt = nameEntered.get()
print(nameEnt)
sql = "SELECT * FROM attendance WHERE name="%s"
val = (nameEnt)
print(mycursor.execute(sql, val))
myresult = mycursor.fetchall()
for x in myresult:
print(x)
I would like to pass the string in 'nameEnt' into the SQL query using python. I'm currently using the mysql-connector package. The program keeps telling me that my syntax is incorrect. I can execute the query in SQL directly without any problem.
I have also tried
sql = "SELECT * FROM attendance WHERE name= "+nameENt
Do not combine SQL strings with data unless you know what you are doing. Doing so is a sure way to get yourself an SQL injection vulnerability.
Your original code was almost correct. First, as the comments noted, you don't need the quotes around %s:
sql = "SELECT * FROM attendance WHERE name=%s"
Then, your second parameter to cursor.execute() is a tuple, but in Python, to make a single-element tuple, wrapping it in brackets isn't enough:
my_element = 12345
not_a_tuple = (my_element)
type(not_a_tuple) == int
real_tuple = (my_element,) # note the comma at the end
type(real_tuple) == tuple
Applying these to your code, you get:
nameEnt = nameEntered.get()
print(nameEnt)
sql = "SELECT * FROM attendance WHERE name=%s"
val = (nameEnt,)
print(mycursor.execute(sql, val))
myresult = mycursor.fetchall()
for x in myresult:
print(x)
you can try:
sql = "SELECT * FROM attendance WHERE name = %s",(nameEnt)
Or:
sql = "SELECT * FROM attendance WHERE name = {}".format(nameEnt)
I'm running SQL Query using python-Django RAW Query..!!
I'm using IN() function to pass my tuple in the query.
My code looks like this...
Here I am getting the list of dnc_domains and dnc_company from a json/function
dnc_domain_names = list(map(lambda x: get_domain_name(x), dnc_websites))
dnc_company_names = list(map(lambda l: l.lower(), list(filter(None, list(map(lambda x: x['company_name'], dnc_info))))))
QUERY:
select_query = """
select c.id
from (
select id, lower(company_name) as c_name,substring(website from '(?:.*://)?(?:www\.)?([^/]*)') as website_domain,
from contacts
where campaign_id = %s
) c
where
c.c_name IN %s
OR c.website_domain IN %s
"""
Executing Query:
with connection.cursor() as cursor:
cursor.execute(select_query, (campaign.id,tuple(dnc_company_names),tuple(dnc_domain_names))
matching_contact_ids = cursor.fetchall()
But, there is a case when any dnc_company_names or dnc_domain_name is empty [] then my Query throws an Error otherwise if there at least 1 element in any of them then it works fine.
SQL Error:
syntax error at or near ")"
LINE 5: WHERE id IN ()
^
So, help me to tackle this error. SQL should handle both empty or non empty tuples.
This is solved by providing NULL values in list
if not dnc_company_name:
dnc_company_name = [None]
finally, in my question, I am converting dnc_company_name into tuple.
and it solved my problem.
The right part of the IN must be a subquery returning exactly one column:
https://www.postgresql.org/docs/current/static/functions-subquery.html#FUNCTIONS-SUBQUERY-IN
I tried
SELECT *
FROM table_with_data
WHERE toto IN (SELECT * FROM empty);
which throws this error:
ERROR: subquery has too few columns
I guess you should provide something as IN (NULL) in the case your columns are strictly NOT NULL.
I have troubles using a simple sql statement with the operator IN through pymssql.
Here is a sample :
import pymssql
conn = pymssql.connect(server='myserver', database='mydb')
cursor = conn.cursor()
req = "SELECT * FROM t1 where id in (%s)"
cursor.execute(req, tuple(range(1,10)))
res = cursor.fetchall()
Surprisingly only the first id is returned and I can't figure out why.
Does anyone encounter the same behavior ?
You're trying to pass nine ID values to the query and you only have one placeholder. You can get nine placeholders by doing this:
ids = range(1,10)
placeholders = ','.join('%s' for i in ids)
req = "SELECT * FROM t1 where id in ({})".format(placeholders)
cursor.execute(req, ids)
res = cursor.fetchall()
As an aside, you don't necessarily need a tuple here. A list will work fine.
It looks like you are only passing SELECT * FROM t1 where id in (1). You call execute with the tuple but the string only has one formatter. To pass all values, call execute like this:
cursor.execute(req, (tuple(range(1,10)),))
This will pass the tuple as first argument to the string to format.
EDIT: Regarding the executeone/many() thing, if you call executemany and it returns the last instead of the first id, it seems that execute will run the query 10 times as it can format the string with 10 values. The last run will then return the last id.
I am trying to query a mysql db from python but having troubles generating the query ebcasue of the wildcard % and python's %s. As a solution I find using ?, but when I run the following,
query = '''select * from db where name like'Al%' and date = '%s' ''', myDateString
I get an error
cursor.execute(s %'2015_05_21')
ValueError: unsupported format character ''' (0x27) at index 36 (the position of %)
How can i combine python 2.7 string bulding and sql wildcards? (The actual query is a lot longer and involves more variables)
First of all, you need to escape the percent sign near the Al:
'''select * from db where name like 'Al%%' and date = '%s''''
Also, follow the best practices and pass the query parameters in the second argument to execute(). This way your query parameters would be escaped and you would avoid sql injections:
query = """select * from db where name like 'Al%%' and date = %s"""
cursor.execute(query, ('2015_05_21', ))
Two things:
Don't use string formatting ('%s' % some_var) in SQL queries. Instead, pass the string as a sequence (like a list or a tuple) to the execute method.
You can escape your % so Python will not expect a format specifier:
q = 'SELECT foo FROM bar WHERE zoo LIKE 'abc%%' and id = %s'
cursor.execute(q, (some_var,))
Use the format syntax for Python string building, and %s for SQL interpolation. That way they don't conflict with each other.
You are not using the ? correctly.
Here's an example:
command = '''SELECT M.name, M.year
FROM Movie M, Person P, Director D
WHERE M.id = D.movie_id
AND P.id = D.director_id
AND P.name = ?
AND M.year BETWEEN ? AND ?;'''
*Execute the command, replacing the placeholders with the values of
the variables in the list [dirName, start, end]. *
cursor.execute(command, [dirName, start, end])
So, you want to try:
cursor.execute(query,'2015_05_21')
I am working with a database and in column_x some variables were NULL. As someone did not prefer this we decided to change this to 'None'. Now I used the following command to change that in Python:
query = "update stone set results = 'None' where results is null;"
But when I do:
query = "SELECT * FROM stone where part = 'ABC';"
I get an output 'x','y','z',None,'a'
But when I do:
query = "SELECT * FROM stone where part = 'ABC' and results = 'None';"
I get () returned. This is probably because 'None' does not exists. Thus short question long, how do I change None -> 'None' via Python?
I wasn't sure if when you said None you meant null.
If you intended None to mean null you can use something like this (MYSQL):
sql = "UPDATE stone set results=\'None\' where results is null"
cursor = conn.Execute($sql)
rows = cursor.Affected_Rows()
For Oracle, execute this SQL:
sql = "UPDATE stone set results=''None'' where results='None'"
cursor = conn.Execute($sql)
rows = cursor.Affected_Rows()
For MYSQL, you need to use a backslash to escape the tick - something like
sql = "UPDATE stone set results=\'None\' where results='None'"
cursor = conn.Execute($sql)
rows = cursor.Affected_Rows()
See also
http://phplens.com/lens/adodb/adodb-py-docs.htm
http://www.codersrevolution.com/index.cfm/2008/7/13/Just-when-you-felt-safe-SQL-Injection-and-MySQL