SQLAlchemy pass parameters with like '%STRING%' in raw sql - python

I have a sql:
select *
from my table
where exists (
select
from unnest(procedure) elem
where elem like '%String%'
)
It works well when directly execute in database ide.
My question is how can I set 'String' as a parameters ?
I have tried:
String = 'hello world'
my_query = '''
select *
from my_table
where exists (
select
from unnest(procedure) elem
where elem like '% :String %'
)
'''
result=connection.execute(text(my_query),String=String)
However it returns nothing,I think maybe "like %" is special ?
Any friend can help ?

I think a better solution is to put the percent signs in the variable itself, and have only :String in the query:
String = '%hello world%'
my_query = '''
...
where elem like :String
'''

Related

Problem in Where clause of SQL Query while comparing String using python variable

Im trying to select from MS Access Database table in python WHERE Itemname is equal to some particular string which is stored in variable , while comparing that string directly in where clause with LIKE operator it is working fine but when i`m trying to pass this string through variable it is showing me syntex error.
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE 'XYZ' "
cursor2.execute(query)
This is working fine
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE %s "
cursor2.execute(query,(Itemname,))
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE {}".format(Itemname)
cursor2.execute(query)
None of the Two above options are working ,Pls point out if there is any syntex problem
This is working finally
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname = ? "
cursor2.execute(query,[itemname])

Pass a python variable into an SQL query

I am working on Databricks and I am trying to pass a python variable into a SQL query:
series_name "LogTest"
query = """SELECT * FROM results_table
WHERE name = $series_name
"""
spark.sql(query).toPandas()
I tried with $ but it does not work.
How do I do this?
Regards
In this case, your variable and queries are just strings. You can do:
query = f"""SELECT * FROM results_table
WHERE name = '{series_name}'
"""
... in python 3. Remember that your query string needs the single quotes around the inserted variable. However, for certain variables, you may need to pass the variable directly to the spark module so it can interpret it. I use pyodbc a lot and would do this:
query = f"""SELECT * FROM results_table
WHERE name = ?"""
cursor.execute(query, series_name)
Following will also work,
series_name = "LogTest"
spark.sql("SELECT * FROM results_table WHERE name = " + series_name).toPandas()
we can also try the following.
series_name = "LogTest"
query = "SELECT * FROM results_table WHERE name = {}".format(series_name)
spark.sql(query).toPandas() #

How to deal with multi line SQL Query in Python?(Subquery as variable)

I would like to use some long SQL Query in python like below
def method(qa_cursor):
sub_query = """ Select Some Query
From A
where A.id = XXX """
main_query = """ Select a, b, c ...
From B join (""" + sub_query + """) A on ~~~
where ~~"""
qa_cursor.execute(main_query)
results = qa_cursor.fetchall()
return results
But I am getting errors to use right syntax.
How do i make this possible??
Thank you.
It was my typo.. This question is solved. Above How I used is correct

how to see full query with values in ponyorm

Today i am using the sql_debug(True) that helps me to see the queries but without the values.
How could i see how ponyorm translate the query with values ?
Thank you very much.
This is an example of query i'm using.
with db_session:
access = select(p for p in Access if raw_sql('( lower(first_name) = lower($first_name) and lower(last_name) = lower($last_name) ) '
'or ( lower(first_name) = lower($last_name) and lower(last_name) = lower($first_name) ) '
'or (lower(facebook_url) = lower($facebook_url)) '
'or (lower(twitter_url) = lower($twitter_url)) '
'or (lower(linkedin_url) = lower($linkedin_url)) '))
.order_by(desc(Access.twitter_url),desc(Access.facebook_url),desc(Access.linkedin_url),
desc(Access.facebook_url))
print(access.get_sql())
I use
logging.getLogger(__name__).debug('SQL:\n\n\t\t\t%s\n', '\n'.join(unicode(x) for x in request._construct_sql_and_arguments()[:2]).replace('\n', '\n\t\t\t'))
for that.
For example,
19:30:01.902 data.py:231 [DEBUG] SQL:
SELECT "x"."_id", "x"."filename", "x"."_created", "x"."_updated"
FROM "reports" "x"
WHERE "x"."_id" <= ?
AND "x"."_created" >= ?
(50, '2019-04-17 19:30:01.900028')
will be printed out.
You can use set_sql_debug(debug=True, show_values=True).
Reference here.
There is a method called get_sql()
query_obj = select(c for c in Category if c.name.startswith('v'))
sql = query_obj.get_sql()
print(sql)
output:
SELECT "c"."id", "c"."name"
FROM "category" "c"
WHERE "c"."name" LIKE 'v%%'
code continue:
for obj in query_obj:
print('id:', obj.id, 'name:', obj.name)
output:
id: 1 name: viki
here is a link to the docs https://docs.ponyorm.com/api_reference.html#Query.get_sql
You can log the sql or simply print it.
Update:
OP updated the question:
If the sql query has a variable like $name it is passed as a sql parameter.
first_name = 'viki'
query = select(c for c in Category if raw_sql('( lower(name) = lower($first_name))'))
query.get_sql()
so get_sql() will return the value with a placeholder, and the output will look like this:
'SELECT "c"."id", "c"."name", "c"."age"\nFROM "Category" "c"\nWHERE ( lower(name) = lower(?))'
If we want no placeholders should be there in the query then we can avoid passing direct sql to query and instead build it separately in python.
Like this:
query = select(c for C in Category if c.name == 'viki')
query.get_sql()
output:
'SELECT "c"."id", "c"."name", "c"."age"\nFROM "Category" "c"\nWHERE "c"."name" = \'viki\''

Error: Cursor' object has no attribute '_last_executed

I have this cursor
cursor.execute("SELECT price FROM Items WHERE itemID = (
SELECT item_id FROM Purchases
WHERE purchaseID = %d AND customer_id = %d)",
[self.purchaseID, self.customer])
I get this error
'Cursor' object has no attribute '_last_executed'
But when I try this:
cursor.execute("SELECT price FROM Items WHERE itemID = (
SELECT item_id FROM Purchases
WHERE purchaseID = 1 AND customer_id = 1)",
)
there is no error. How do I fix this?
I encountered this problem too. I changed the %d to %s, and it is solved. Wish this is useful for you.
The problem is that you are not making substitutions properly in your select string. From docs:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
So, it should be:
cursor.execute("SELECT price FROM Items WHERE itemID = (
SELECT item_id FROM Purchases
WHERE purchaseID = ? AND customer_id = ?)",
(self.purchaseID, self.customer))
The reason is that you are using '%d'. When you use '%' in SQL, the execute will interpret the '%' as the format. You should write your statement like this:
cursor.execute("SELECT price FROM Items WHERE itemID = (
SELECT item_id FROM Purchases
WHERE purchaseID = %%d AND customer_id = %%d)",
[self.purchaseID, self.customer])
Depending on your SQL package, you may need to use cursor.statement instead.
Worked for me using double %%
"SELECT title, address from table t1, table t2 on t1.id=t2.id where t1.title like '%%Brink%%' "
from django.db import connection
print(connection.queries)
The code above should display all the requeries that are executed on the request.

Categories