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.
Related
Error in python
Code running in DB
I'm trying to pull data from the sql database, but the second part of the code after the 'case' is not readable. But this one when in sql works, but does not work in Python. Help please
cursor.execute('SELECT distinct created_date from analitics','case when cast("("created_date")") = cast(now() as DATE) then (Yes) else (No) end FROM analitics')
Your python code is incorrect. Update it as below:
cursor.execute('SELECT distinct created_date from analitics, case when cast(created_date) = cast(now() as DATE) then "Yes" else "No" end FROM analitics')
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)
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
I am receiving an error when trying to write data to a database table when using a variable for the table name that I do not get when using a static name. For some reason on the line where I insert, if I insert an integer as the column values the code runs and the table is filled, however, if I try to use a string I get a SQL syntax error
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS %s' %data[1])
sql ="""CREATE TABLE %s (IP TEXT, AVAILIBILITY INT)""" %data[1]
cursor.execute(sql)
for key in data[0]:
cur_ip = key.split(".")[3]
cursor.execute("""INSERT INTO %s VALUES (%s,%s)""" %(data[1],key,data[0][key]))
db.commit()
the problem is where I have %(data[1], key, data[0][key]) any ideas?
It's a little hard to analyse your problem when you don't post the actual error, and since we have to guess what your data actually is. But some general points as advise:
Using a dynamic table name is often not way DB-systems want to be used. Try thinking if the problem could be used by using a static table name and adding an additional key column to your table. Into that field you can put what you did now as a dynamic table name. This way the DB might be able to better optimize your queries, and your queries are less likely to get errors (no need to create extra tables on the fly for once, which is not a cheap thing to do. Also you would not have a need for dynamic DROP TABLE queries, which could be a security risk.
So my advice to solve your problem would be to actually work around it by trying to get rid of dynamic table names altogether.
Another problem you have is that you are using python string formatting and not parameters to the query itself. That is a security problem in itself (SQL-Injections), but also is the problem of your syntax error. When you use numbers, your expression evaluates to
INSERT INTO table_name VALUES (100, 200)
Which is valid SQL. But with strings you get
INSERT INTO table_name VALUES (Some Text, some more text)
which is not valid (since you have no quotes ' around the strings.
To get rid of your syntax problem and of the sql-injection-problem, don't add the values to the string, pass them as a list to execute():
cursor.execute("INSERT INTO table_name VALUES (%s,%s)", (key, data[0][key]))
If you must have a dynamic table name, put that in your query string first (e.g. with % formatting), and give the actual values for your query as parameters as above (since I cannot imagine that execute will accept the table name as a parameter).
To put it in some simple sample code. Right now you are trying to do it like this:
# don't do this, this won't even work!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO %s VALUES (%s, %s)" % (table_name, user_name, user_age)
cursor.execute(query)
That creates query
INSERT INTO some_table VALUES (Peter Smith, 100)
Which cannot work, because of the unquoted string. So you needed to do:
# DON'T DO THIS, it's bad!
query = "INSERT INTO %s VALUES ('%s', %s)" % (table_name, user_name, user_age)
That's not a good idea, because you need to know where to put quotes and where not (which you will mess up at some point). Even worse, imagine a user named named Connor O'Neal. You would get a syntax error:
INSERT INTO some_table VALUES ('Connor O'Neal', 100)
(This is also the way sql-injections are used to crush your system / steal your data). So you would also need to take care of escaping the values that are strings. Getting more complicated.
Leave those problems to python and mysql, by passing the date (not the table name) as arguments to execute!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO " + table_name + " VALUES (%s, %s)"
cursor.execute(query, (user_name, user_age))
This way you can even pass datetime objects directly. There are other ways to put the data than using %s, take a look at this examples http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html (that is python3 used there, I don't know which you use - but except of the print statements it should work with python2 as well, I think).
I'm a postgres newbie and am having some issues querying a text field in postgresql using Python. What is the correct syntax that will allow me to search the content of column "body" from table "jivemessage" out of database "postgres"?
try:
conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='<password>'")
except:
print "cannot connect"
i = 'test'
cur = conn.cursor()
cur.execute('SELECT * from jivemessage WHERE body LIKE "%'+i+'%"')
Keep getting the following error:
ProgrammingError: column "%test%" does not exist
Thanks for any help.
You are not quoting the query properly. Don't use string concatenation here, use SQL parameters instead:
cur.execute('SELECT * from jivemessage WHERE body LIKE %s', ("%{}%".format(i),))
Here, the %s placeholder signals to the database driver that the first value of the second argument should be placed there when querying.
This leaves the interpolation up to the database driver, giving the database the opportunity to optimize for the query once, even if you were to reuse the same query.
It also prevents SQL injection attacks better than you could yourself, and most of all, guarantees that the correct quoting rules are followed.