How can I use LIKE operation on a parameter? [duplicate] - python

I've got an argument tag and I perfomed this way:
cursor.execute("SELECT * FROM posts WHERE tags LIKE '%?%'", (tag,))
but it doesn't seem to work.
I'm new to sqlite, please tell me how to fix it. Thx !

Apply the wildcards to the parameter, not the SQL:
cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (f'%{tag}%',))
The ? SQL parameter interpolation adds quoting for you, so your query ends up as '%'value'%', which is not valid SQL.

Remove the %:
cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (tag,))
This should format it as you wanted. For example, if tag == 'test' the full query would be:
SELECT * FROM posts WHERE tags LIKE 'test'

Related

Passing Safe Query Parameters with SQLite in Python

I am working on a project that uses a HTML text input to retrieve data from a SQLite database.
The idea goes like this : the user types string representing a product number and I look into my database for that string.
I have tried to make my query safe for SQL injection as suggested in this tutorial because the data does not come from me.
cursor.execute("SELECT product_number FROM price_history WHERE product_number = %s';", (user_input, ))
However, when I try to execute my code, I get :
sqlite3.OperationalError: near "%": syntax error
There's an extra ' after %s.
Read the first paragraphs of the python docs on sqlite3 that show the correct way to use placeholders.
cursor.execute("SELECT product_number FROM price_history WHERE product_number = (?)", (user_input, )) should work.

Problem with postgres passing parameters in python

I have this code which take title, or isbn, or an author of a book and retrieve all matching data from database.
The problem is with the passing parameter line, it retrieve only the first record, regardling of the data that the user enter.
I tried to use the select statement it in the data base console and it retrieve the correct statement, which i understand that the cur.execute that pass the parameters line is not right. Can you help me with this and thanks in advance.
This is the code
class Searchb:
def __init__(self,isbn,author,title):
self.isbn=isbn
self.author=author
self.title=title
def booksearch(self):
query= "select author,title from books where isbn LIKE '%%s%%' OR author LIKE '%%s%%' OR title like '%%s%%' "
cur.execute(query,(self.isbn,self.author,self.title),)
book=cur.fetchmany()
You are using cur.fetchmany() without any paramters. From the docs:
The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s arraysize determines the number of rows to be fetched.
arraysize defaults to 1, which is why you are only getting 1 row. Either specify something higher iterate until you get no more results or just use cur.fetchall()
The problem was in the select statement and I could find myself the correct syntax of select statement with Like at the same time you pass parameters to database; postgres
query="select author,title from books where isbn LIKE %s or author like %s or title like %s "
book_to_search=(self.isbn,self.author,self.title)
cur.execute(query,book_to_search)
book=cur.fetchall()
THANKS FOR EVERYONE!

SQL error with sqlite in python

i have a hopefully simple Problem with an SQL-command
Code:
c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = "+str(user_id))
pic_num is a column in the database and user_id is an Integer in the database
I thought everything would be right but i get this
Error:
sqlite3.OperationalError: near ")": syntax error
this Information doesn't help me at all
The correct way to use python's db-api is to use placeholders in your SQL query and pass query values along, ie:
c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id=?", [user_id,])
Note that this might not necessarily solve your problem but since you didn't post the schema nor the user_id value we can't try & reproduce the issue.
You should python sqlite module's substitution instead like so:
c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = ?", (user_id, ))
Thank you all for the fast answers!
c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = ?", (str(user_id), ))
this finally worked :)
I already have written some libs which should handle SQL-injection (they test the Input for quotes but you're right im very new with SQL :D)

How to check if a table exists using python?

I want to check whether the table exists or not before inserting the data.
This is what i have tried:
def checkTables(tablename):
stmt = "SHOW TABLES LIKE %s"%tablename
cursor.execute(stmt)
result = cursor.fetchone()
return result
But it gives me error saying:
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 'ctg_payload3' at line 1
Maybe it is not the best way.
As for my opinion, I will show tables;, then search the result.
And, I you cannot execute show tables like tablename;, no syntax like that.
edit 1
If you must do it in sql, use
show table status like 'table_name';
' is needed for this sql.
Try this query string :SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%' or
this one
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE '%tablename%'
Good luck
Try this.
def checkTables(tablename):
stmt = "SHOW TABLES LIKE '%s' "% ('%'+str(tablename)+'%')
cursor.execute(stmt)
result = cursor.fetchone()
return result

Can I use string formatting while querying a database in python

I have been learning sqlite3 in python and I was wondering if I could use string formatting to edit the database or query it.
e.g. - SELECT %s FROM (table_name) where % can be the users input stored in a variable?
I tried it but it doesn't work so can someone please give me a working example.
Any help is appreciated. Thanks
Guys i tried this:
dursor = conn.execute("SELECT id FROM books")
# this helps find the correct id for storing in the database
for i in dursor:
lis.append(i[0])
command = """INSERT INTO books VALUES ({0}, {name}, {author})""".format(lis[-1] + 1, name=client_name, author = client_author)
and then
conn.execute(command)
but it returns no such column (name)
when i tried the same query in khan academy sql it worked why not here?
You can place question mark on your query string and pass the parameters from user input while calling the .execute() as a tuple.
Though i don't believe you are using it in a production. If it is the case than first take the data from user, sanitize it and see if you really want to let the user do what he actually wants to do.
Hope this helps:
param1 = sys.argv[1]
param2 = sys.argv[2]
query = "SELECT ? FROM (table_name) where id = ?"
cursor.execute(query, (param1,param2))
I'm unsure if you can do it in sqlite3 but I'd be looking for any alternative method if I were you. Are you REALLY wanting to allow the user to be able to actually alter your SQL on the fly? That is a potentially huge security hole you'd be creating.
e.g. user can essentially alter...
select ? from innocentTable
...to...
select * from tblUser -- from innocentTable
...and trawl your entire user table, just takes a bit of guess work to come up with the object names.
I'd suggest you read up on SQL Injection Attacks then look for an alternative way to achieve what you've suggested.

Categories