What's the mistake in the following query? - python-3.x

I have the following query:
strsql = """SELECT referencia, concepto, sfamilia, pvp, puc FROM almacen2 WHERE concepto like '*YATEKOMO*'"""
I use this sentence in python with the Access Driver.
When I execute this in my code:
strsql = """SELECT referencia, concepto, sfamilia, pvp, puc FROM almacen2"""
I get a lot of results.
And when I try to execute the query with the tag LIKE in Access directly, I get 8 results.
What's my mistake so I get results out of my code and not in it?

Use % instead of *.
Or do RegEx with concepto ~ 'YATEKOMO'
Oops, I can see that this is about ACCESS. My answer fits more to PostgreSQL.

Related

Difficult in converting to strings from a list

I have a list which is in below format
A = [ "machine's code" ,"max's code"]
I want to convert to that list to string and pass it to a query. I am using python for this.
I am trying with below query and not giving required results
for i in A:query=Select * from table where name='"+str(A)+"'"
Expected code should be :
Select * from table where name="machine's code"
list_of_queries = []
for element in A:
query = f'Select * from table where name="{el}"'
list_of_queries.append(query)
as pointed out by others here, this pattern should be only used internally, as it creates some sql injection security risks.

Update multiple column with bind variable using cx_Oracle.executemany()

I have been trying to update some columns of a database table using cx_Oracle in Python. I created a list named check_to_process which is a result of another sql query. I am creating log_msg in the program based on success or failure and want to update same in the table only for records in check_to_process list. When I update the table without using bind variable <MESSAGE = %s>, it works fine. But when I try to use bind variable to update the columns it gives me error :
cursor.executemany("UPDATE apps.SLCAP_CITI_PAYMENT_BATCH SET MESSAGE = %s, "
TypeError: an integer is required (got type str)
Below is the code, I am using:
import cx_Oracle
connection = cx_Oracle.connect(user=os.environ['ORA_DB_USR'], password=os.environ['ORA_DB_PWD'], dsn=os.environ['ORA_DSN'])
cursor = connection.cursor()
check_to_process = ['ACHRMUS-20-OCT-2021 00:12:57', 'ACHRMUS-12-OCT-2021 16:12:01']
placeholders = ','.join(":x%d" % i for i,_ in enumerate(check_to_process))
log_msg = 'Success'
cursor.executemany("UPDATE apps.SLCAP_CITI_PAYMENT_BATCH SET MESSAGE = %s, "
"PAYMENT_FILE_CREATED_FLAG='N' "
"WHERE PAYMENT_BATCH_NAME = :1",
[(i,) for i in check_to_process], log_msg, arraydmlrowcounts=True)
Many thanks for suggestions and insights!
Your code has an odd mix of string substitution (the %s) and bind variable placeholders (the :1). And odd code that creates bind variable placeholders that aren't used. Passing log_msg the way you do isn't going to work, since executemany() syntax doesn't support string substitution.
You probably want to use some kind of IN list, as shown in the cx_Oracle documentation Binding Multiple Values to a SQL WHERE IN Clause. Various solutions are shown there, depending on the number of values and frequency that the statement will be re-executed.
Use only bind variables. You should be able to use execute() instead of executemany(). Effectively you would do:
cursor.execute("""UPDATE apps.SLCAP_CITI_PAYMENT_BATCH
SET MESSAGE = :1
WHERE PAYMENT_BATCH_NAME IN (something goes here - see the doc)""",
bind_values)
The bottom line is: read the documentation and review examples like batch_errors.py. If you still have problems, refine your question, correct it, and add more detail.

Using sql string as sql statement in odbc power query in excel

I am looking to use a string that takes in some parameters from my cells and use it as my sql statement like so:
" select * from table where " & data_from_cells & " group by ...;"
store it as sqlstring
let
mystring = sqlstring,
myQuery = Odbc.Query("driver={Oracle in etc etc etc", mystring)
and I run into this error
Formula.Firewall: Query '...' (step 'myQuery') references other queries or steps, so it may not directly access a data source. Please rebuild this data combination.
now apparently I can't combine external queries and another query -- but I am only using passed-on parameters from Excel for my sql string? I am hoping to use WITH keyword as well to make nested queries using parameters but it doesn't even let me combine values from excel with an sql statement..
to be clear, the data_from_cells was transformed and formatted as a string.
When queries that do stuff are called by other queries that do other stuff, sometimes you can get firewall issues.
The way to get around that is for everything to be done in a single query.
The way to get around that without ending up with horrible code is to change your called queries from returning the result to functions that return the result.
For sqlstring:
() => " select * from table where " & data_from_cells & " group by ...;" // returns a function that gets the query string when called
Then your "myQuery" query can be
let
mystring = sqlstring(), //note the parentheses!
myQuery = Odbc.Query("driver={Oracle in etc etc etc", mystring)

What is the best way to pass multiple string variables to a query string in python3

I need to create a dynamic query based on two string parameters:
description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"
Note:
there might be single quote and double quotes in both description and comment.
How do I use formatted %s to generate the query string?
Thank you very much.
UPDATE:
Thanks to Green Cloak Guy (his/her answer has minors to be corrected), the right query is:
query = f"insert into case(description, comment) value(\'{description}\', \'{comment}\')"
Use an f-string.
query = f"insert into case({description}, {comment}) value({description}, {comment})"
Don't use any type of string formatting to do actual database queries - that leads to you having a SQL Injection problem. Use a database library instead, that properly sanitizes the data.
But if all you need to do is parse some variables into a string, this is more flexible than the % formatting that other languages tend to use (and that's technically still available in python via "some_string %s %s %s" % (str1, str2, str3)")

when I shoud use format() function and str() function. which one is better?

I am stuck to find out better one between str() and format() in python
"SELECT schools.deis_income , schools.school_name,SUM(money.coin_in_amount) AS coinamount, SUM(money.note_in_amount) AS noteamount , SUM(money.coffee_coin_in_amount) AS coffeeamount , SUM(money.coin_out_amount) AS coinoutamount, SUM(money.note_out_amount) AS noteoutamount FROM money_transactions AS money JOIN school_admin_details AS sa on sa.id = money.school_admin_id JOIN schools ON schools.id=sa.school_id WHERE sa.school_id ={school_id} AND money.transaction_time BETWEEN '{start_date}' AND '{end_date}' GROUP BY schools.id".format(school_id=school_id,start_date=start_date,end_date=end_date)
I use format function here. can I use str() ?
please tell me which one give me quick result, str() or format() ???
If your question is which of this:
foo = "some text " + str(some_var) + " and some other text"
or this:
foo = "some text {} and some other text".format(var)
is "better", the general consensus is very clear: string formatting is much easier to read and maintain and the one pythonic way to go.
Now for your particular example, the answer is that both are totally wrong - unless you're ok to give full access to your database to even the most inept script kiddie. For SQL queries, the proper solution is to use prepared statements, where your db connector will take care of proper formatting and sanitizing of the values:
# assumes MySQL - for other vendors check your own
# db-api connector's doc for the correct placeholder
query = "SELECT somefield FROM mytable where somedate > %(somedate)s and something_else = %(someval)s"
cursor.execute(query, {"somedate": some_date, "someval": 42})

Resources