Insert String in Python SQLite Statement - python

I'm trying to insert a string into a SQLite Select statement in python. When I try this code:
cur.execute("SELECT * FROM DB WHERE employeeNum = '?'",(empNum,))
I get this error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
When I try this code:
cur.execute("SELECT * FROM DB WHERE employeeNum = '",empNum,"'")
I get this error:
TypeError: function takes at most 2 arguments (3 given)
How do I query this string? Sorry I'm new to python. Any help would be greatly appreciated!

Do not use string formatting to insert query parameters into the query - this would make sql injections possible, you would have problems with characters that need to be escaped, with data type conversions etc.
Eliminate the quotes around ? and continue using parameterized query parameters:
cur.execute("SELECT * FROM DB WHERE employeeNum = ?", (empNum, ))
The quotes around ? made sqlite interpret ? as a string, not a placeholder.
Also see similar problem:
SQLite parameter substitution and quotes

Related

Python MySql SELECT query formatting [duplicate]

This question already has an answer here:
Dynamic SQL Queries with Python and mySQL
(1 answer)
Closed 3 months ago.
I am unable to execute the following statement I keep getting SQL syntax errors.
According to all the examples I can find this should work
Any help will be greatly appreciated.
d2 = df.iloc[-1,:]
q = symbol+'_ivol'
query = """SELECT close FROM %s WHERE date = %s"""
VALUES= (q, d2[1])
cursor.execute(query, VALUES)
ivol = cursor.fetchall()
conn.close()
Query parameters in SQL are not just string substitution. You can't use a query parameter for a table identifier. Parameters can only be used where you would normally use a quoted string literal or numeric literal.
Stated another way, all the identifiers must be fixed in the query string before you prepare it, because identifiers must be validated during the prepare phase, to make sure the table is a valid identifier, and that the table exists. You can't pass the name of a table identifier after the query has been prepared.
The Python driver unfortunately makes this more confusing because it uses %s instead of MySQL's own ? symbol for the parameter placeholder. This makes developers naturally think that %s is simply string substitution, like it is for Python string formatting.
So there's %s and there's %s, and they are handled differently. I know, it's confusing.
So you can do a plain string-formatting substitution to put your table into the query string:
query = """SELECT close FROM %s WHERE date = %%s""".format(q)
But it's more idiomatic for modern Python to use f-string formatting:
query = f"""SELECT close FROM `{q}` WHERE date = %s"""
I put back-ticks around the table name, just in case it's a SQL reserved keyword or something.
Then the other %s is an actual query parameter, because it works as a scalar value in the SQL expression. In this query, there is just one query parameter.
VALUES= [ d2[1] ]
cursor.execute(query, VALUES)

queryText with WHERE condition in aws_s3.query_export_to_s3 not working

Trying to execute the query on lambda in python using psycopg2.
query = "SELECT * FROM aws_s3.query_export_to_s3('SELECT * from sample WHERE name='text1'','s3-bucket-name','file-path')".
Gives me an error - syntax error at or near "text1".
Meanwhile, this query is running fine with name with type number but not working with the string type, and also this query is working fine without query_export_to_s3.
It seems to me like query_export_to_s3 can't work with string in WHERE condition.
Thanks in advance for any suggestion
Escape your single quotes with single quotes.
query = "SELECT * FROM aws_s3.query_export_to_s3('SELECT * from sample WHERE name=''text1''','s3-bucket-name','file-path')"

Syntax for SQL via python script (Incorrect syntax near ',')

I am using SQL server and need to run the following SQL via Python script
SELECT DISTINCT LEN(Wav)-CHARINDEX('.', Wav) FROM <>;
I have tried to play with the String but couldn’t figure out how to work around the dot character.
sql = 'SELECT DISTINCT LEN(Wav)-CHARINDEX({}, Wav) FROM xxx'.format('.')
print(sql)
cursor = conn.cursor()
cursor.execute(sql)
Any idea how to resolve this
Thank you
'.' is the string ., you want "'.'", the string '.'
>>> print("{}".format('.'))
.
>>> print("{}".format("'.'"))
'.'
As #Justin Ezequiel's answer notes, do beware of SQL injections here!
Specifically, unfiltered user inputs can and will cause an SQL injection where unanticipated commands can be run against the target database by breaking out of the raw string. These can do anything your connection has permission to do, such as retrieving, modifying, or deleting arbitrary data.
A traditional approach is to use prepared statements
In Python, you can also use a regex or other test to explicitly error for statements with control characters (if not re.match(r"^[a-zA-Z\d _+-]+$"), s):raise_) or use (trust) an escaping library to do it for you if you must take arbitrary strings.
Use parameters to avoid SQL-injection attacks.
sql = 'SELECT DISTINCT LEN(Wav)-CHARINDEX(?, Wav) FROM xxx' # note placeholder (?)
print(sql)
params = ('.',) # tuple
cursor = conn.cursor()
cursor.execute(sql, params)

Printing SQL string as argument of a cursor object [duplicate]

This question already has answers here:
Python SQLite how to get SQL string statement being executed
(4 answers)
Closed 2 years ago.
Here I see the suggested way of building queries with python and sqlite3:
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
How do I print the query instead of the result? I know it's not a string, and so a "print sql" statement wouldn't work. In my case, I am running flask and I want to have this code responding to an API invocation:
...
cur = conn.cursor()
arguments = (username, password, )
query = 'SELECT * FROM logins where ((username = ?) AND (password = ?));', arguments
return(query)
...
I would expect to see this query, not to execute it. However, I receive this output:
ValueError: too many values to unpack (expected 2)
Furthermore, I didn't see any method that exports the last query issued in the SQLite.
This might not be the answer you're looking for, but you can format the query as a string using python string format and print, before formatting again using db-api within the c.execute() statement. As long as you only format the executed query with db-api, you're not at risk from sql injection.

what does ? mean in python pyodbc module

import pyodbc
cursor.execute("INSERT INTO Testing_Param(Seed_Number,Cycle_Name) VALUES (?,?)",('0','CoupleIn'))
what does the "?" mean in the code?
When I try to replace the ? to %s for the "CoupleIn" which is the string and %d for the "0", why does it appear error message:
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 2 parameters were supplied', 'HY000')
I am new to the pyodbc module to do transfering data from Python into Microsoft SQL server
? is the placeholder for the substitution engine. The cursor.execute function is responsible for properly escaping the values in the tuple and inserting them into the query where the respective question marks are to form a valid query. This keeps you safe from sql injection attacks where normal string interpolation would leave your database vulnerable to attackers.
You can read more about the standard python database apis in PEP-0249 -- Specifically, your database wrapper is using qmark paramstyle.
The two question marks are placeholders for the parameters 0 and CoupleIn, respectively.
This is similar for the text formatting in Python where the placeholder for a variable is %.
See http://mkleehammer.github.io/pyodbc/ under the paragraph Parameters
It is a place holder for parameter values, '0' and 'Couple'. cursor.execute will substitute the values in place of ?s.

Categories

Resources