I tried to write a query with Like command to search for special Name , but i need to get the value from User and i need to read the value but my sql code has problem with "LIKE" section , how can i fix it ?
sql = '''SELECT Name FROM newtest WHERE Name LIKE = %s'''
val = (n)
myobj = mycurs.execute(sql , val)
what's the problem ?
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= %s' at line 1
this is the error
Remove the "=" sign. The LIKE command doesn't use that - see https://www.w3schools.com/sql/sql_ref_like.asp for an example.
If you need to search for non-exact matches (i.e. the name is anywhere inside the column) you can change the query as:
SELECT Name FROM newtest WHERE Name LIKE concat('%', %s, '%')
Related
I was looking at this similar question: Parameterize an SQL IN clause
But the solution is not using Python, so I had to raise a new question:
How do I parameterize a query containing an IN clause, the strings 'ruby','rails','scruffy','rubyonrails' comes from a column of a dataframe
SELECT * FROM Tags
WHERE Name IN ('ruby','rails','scruffy','rubyonrails')
ORDER BY Count DESC
The dataframe df might look like:
column1 column2...
ruby .
rails .
scruffy .
xxx
xxxx
Here's what I've tried:
I converted the first column to a list and name it list, then update the second line in the query:
WHERE Name IN %(list)s
But this gave me an error: sqlalchemy.exc.ProgrammingError: (MySQLdb._exceptions.ProgrammingError) (1064, "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 'where Name IN (('ruby','rails','xxx','xxxx','xxx','' at line 2")
I also tried list = str(list)[1:-1] to remove the square bracket, but then I got error: MySQLdb._exceptions.ProgrammingError: (1064, "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 'where Name IN ('\\'ruby\\', \\'rails\\', \\'xxxxx\\', \\'xxx\\',' at line 2")
My question is what format/datatype I should use for df[column1] to get this working? Can someone help please? Thanks.
The only answer here doesn't work, since I've resolved this, so here's the solution: turns out I only need to convert it to a list (with the square bracket), no need to remove the bracket otherwise it won't work!
Maybe you can convert the column list to a tuple:
col_tuple = tuple(list)
Then use a python f-string in your query:
f"""SELECT * FROM Tags
WHERE Name IN {col_tuple}
ORDER BY Count DESC"""
I'm using Django to make some param filtering, and then I got a filtered queryset like below:
sql_str = str(my_queryset.query)
# print(sql_str)
SELECT `market_accounts`.`agency`, `market_accounts`.`id`, `market_accounts`.`entity`, `market_accounts`.`related_entity`
, `market_accounts`.`type`, `market_accounts`.`our_side_entity`, `market_accounts`.`short_title`, `market_accounts`.`titl
e`, `market_accounts`.`settlement_type`, `market_accounts`.`ae`, `market_accounts`.`sale`, `market_accounts`.`medium`, `m
arket_accounts`.`is_pc`, `market_accounts`.`is_new_customer` FROM `market_accounts` WHERE (`market_accounts`.`entity` LIK
E %madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR `market_accounts`.`short_title` LIKE %madbaby% OR
`market_accounts`.`title` LIKE %madbaby%) ORDER BY `market_accounts`.`id` DESC
And for some reason I want to execute the sql above by pymysql, but error showed like :
# cursor.execute(sql_str)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MyS
QL server version for the right syntax to use near '%madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR `
market_acco' at line 1")
Get Data Error!
Why the sql string generated by django cannot be executed by pymysql?
The sql I put above is what I got from str(queryset.query) directly. It missed ' ' which confused me.
Django generates unquoted strings in str(qs.query) so you shouldn't feed those to a database. These are for debugging purposes, though I agree it's a bit sloppy that they aren't properly quoted, it is mentioned in the source:
# django.db.models.sql.query.Query
def __str__(self):
"""
Return the query as a string of SQL with the parameter values
substituted in (use sql_with_params() to see the unsubstituted string).
Parameter values won't necessarily be quoted correctly, since that is
done by the database interface at execution time.
"""
sql, params = self.sql_with_params()
return sql % params
LIKE pattern should be enclosed in quotes
LIKE '%madbaby'
In your query given
SELECT `market_accounts`.`agency`, `market_accounts`.`id`, `market_accounts`.`entity`, `market_accounts`.`related_entity`
, `market_accounts`.`type`, `market_accounts`.`our_side_entity`, `market_accounts`.`short_title`, `market_accounts`.`titl
e`, `market_accounts`.`settlement_type`, `market_accounts`.`ae`, `market_accounts`.`sale`, `market_accounts`.`medium`, `m
arket_accounts`.`is_pc`, `market_accounts`.`is_new_customer` FROM `market_accounts` WHERE (`market_accounts`.`entity` LIK
E %madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR `market_accounts`.`short_title` LIKE %madbaby% OR
`market_accounts`.`title` LIKE %madbaby%) ORDER BY `market_accounts`.`id` DESC
you clearly missed quotes for all the LIKE patterns
this should have been like this
SELECT `market_accounts`.`agency`, `market_accounts`.`id`, `market_accounts`.`entity`, `market_accounts`.`related_entity`
, `market_accounts`.`type`, `market_accounts`.`our_side_entity`, `market_accounts`.`short_title`, `market_accounts`.`titl
e`, `market_accounts`.`settlement_type`, `market_accounts`.`ae`, `market_accounts`.`sale`, `market_accounts`.`medium`, `m
arket_accounts`.`is_pc`, `market_accounts`.`is_new_customer` FROM `market_accounts` WHERE (`market_accounts`.`entity` LIK
E '%madbaby%' OR `market_accounts`.`related_entity` LIKE '%madbaby%' OR `market_accounts`.`short_title` LIKE '%madbaby%' OR
`market_accounts`.`title` LIKE '%madbaby%') ORDER BY `market_accounts`.`id` DESC
The error says that some error has been occurred just before
%madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR `
market_acco
which was caused by the missing quotes for the pattern.
I've this little query :
id = 'TESTID'
sql = "SELECT ID,PASSWORD FROM USERS WHERE ID = %s"
cursor.execute(sql,(id))
and i'm having the 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 'TESTID''' at line 1
I know this is something about double quotes. I've multiple other query that runs perfectly, but they have like 3 parameters
example :
id = 'TESTID'
GR = 'TEST'
name = 'HELLO'
last_name = 'WORLD'
sql = "INSERT INTO USERS (ID,GR,name,last_name) VALUES (%s,%s,%s,%s)"
cursor.execute(sql,(id,gr,name,last_name))
This one don't have 3 double quote at the beginning and 3 others at the end and runs perfectly so i dont know what to do now.
Thanks you.
One thing you should remember in python is that (7) is the same as 7. For a tuple of length 1, you have to say (7,) (note that important trailing comma).
So change this line:
cursor.execute(sql,(id)) to cursor.execute(sql,(id,)).
I am attempting to write a SQL in python using PYMYSQL, which searches a table for a certain record with a set value, however while this sounds simple I cannot seem to do it below is my query:
SELECT Series_ID FROM series_information WHERE Series_Name "'+data +'"'
where the data is the value that I am searching for however the following error occurs:
pymysql.err.ProgrammingError: (1064, '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 \'"Spice And Wolf"\' at line 1')
The problem I believe is that I am not sure how to properly escape the data value if it has spaces in it and therefore would require quotation marks in the SQL query.
You're missing a comparison (like, =, etc) between Series_Name and data, as well as a ';' on the end of the query.
`'SELECT Series_ID FROM series_information WHERE Series_Name = "'+data +'";'
`SELECT Series_ID FROM series_information WHERE Series_Name "'+data +'"'`
Is not a valid SQL query did you mean:
`'SELECT Series_ID FROM series_information WHERE Series_Name like "'+data +'"'`
I'm using the oursql Python library to talk to a MySQL database. I want to write code to search for users by name or email address. This is the code I have currently:
query = get_query()
cursor.execute("""
SELECT *
FROM users
WHERE full_name LIKE '%?%'
OR email LIKE '%?%';""", (query, query))
This code throws an exception:
ProgrammingError: 0 parameters expected, 2 given
Apparently the parser thinks the question mark is apart of the single-quoted string, and therefore isn't doing the substitution. Any ideas on how to fix this?
The %'s in the argument to LIKE are part of the data you want to pass to the DB-API module's execute method, so they need to be part of the argument you pass for the placeholder, not part of the SQL query itself. For example:
query = '%%%s%%' % (get_query(),)
cursor.execute("""
SELECT *
FROM users
WHERE full_name LIKE ?
OR email LIKE ?;""", (query, query))
I think this would work, too:
query = get_query()
cursor.execute("""
SELECT *
FROM users
WHERE full_name LIKE '%' || ? || '%'
OR email LIKE '%' || ? || '%';""", (query, query))