Error selecting from sql table using mysql placeholders - python

I am trying to select some values within a table that has a column called "Name". That column contains tennis players names. I want to store some statistics for each player in python, but I am having trouble accessing the table. I keep getting a "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 '='Rafael Nadal'' at line 1" As you can see, mysql clearly interprets the %s I had in place of 'Rafael Nadal' correctly, but it still brings up an error. Can anyone help me?
recordTuple = ('Rafael Nadal', )
mySql_insert_query = """SELECT `First_Serve(%)` FROM `serve2` WHERE Name =%s"""
cursor.execute(mySql_insert_query, recordTuple)
aI = cursor.fetchall()[0][0]/100

Since % is used to mark placeholders in the SQL, you have to double it if you want to use it literally.
mySql_insert_query = """SELECT `First_Serve(%%)` FROM `serve2` WHERE Name =%s"""
See How do I escape % from python mysql query

Related

How to do I use %s in a mysql query without errors

I am having some trouble selecting from my database using python to execute a MySql query. I have tried two methods to achieve this, but both methods have returned the error shown below:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s' at line 1
What Id like to do is return the row count (which is always zero or one) when a username parameter is passed. I have looked at other examples where people have had this issue but I cant find a good fix.
The first method I tried was this:
def check_data(username):
sql = """SELECT count(*) FROM tbl_user WHERE username = %s"""
mycursor.execute(sql, username)
#do something with the data
I then tried using SELECT (CASE WHEN (uname = %s) THEN TRUE ELSE FALSE END) AS IsEmtpy FROM tbl_user limit 1;
This works database side, but still throws the same error when run in the application. I tried wrapping the %s like '%s' but it didn't help.
Any suggestions?
You're missing enclosing the string between quotes (singles or doubles).
You can check the query you're executing by printing it before the mycursor.execute statement, but basically you're sending MySQL something like SELECT count(*) FROM tbl_user WHERE username = foobar.
Try fixing it with SELECT count(*) FROM tbl_user WHERE username = '%s'.
On a side note, your approach is vulnerable to SQL Injection. You should check the documentation of the tool you're using to connect to the DBMS for "prepared statements".

How to make the SQL Injection on INSERT work on SQLite

I don't know how to make this SQL Injection work in SQLite. I'm using a function in Python that connects to a database and inserts a string.
I have "database.db" that has two tables: "feedback" and "users".
The feedback table has 1 column: message.
The users table has 2 columns: username and password.
def send_feedback(feedback):
conn = sqlite3.connect("database.db")
curs = conn.cursor()
curs.execute("INSERT INTO feedback VALUES ('%s')" % (feedback))
print(curs.fetchall())
conn.close()
I know that the execute function allows me to make a single query to the database, so I can't use ";" to
make multiple queries.
What I have tried, is to make the string look like this:
a') SELECT password FROM users --
feedback = "INSERT INTO feedback VALUES ('a') SELECT password FROM users --')"
But this gives me the following error:
sqlite3.OperationalError: near "SELECT": syntax error
So I've tried to use the UNION command:
a') UNION SELECT password FROM users --
feedback = "INSERT INTO feedback VALUES ('a') UNION SELECT password FROM users --')"
This one works but the fetchall function returns an empty list.
Most SQL injections result in nothing useful to the perpetrator, just a syntax error.
For example, pass the string "I'm not satisfied" to this feedback function and the extra ' character would cause the quotes to be imbalanced, and this would result in an error, causing the INSERT to fail.
sqlite3.OperationalError: near "m": syntax error
That's technically SQL injection. The content interpolated into the query has affected the syntax of the SQL statement. That's all. It doesn't necessarily result in a successful "Mission: Impossible" kind of infiltration.
I can't think of a way to exploit the INSERT statement you show to make it do something clever, besides causing an error.
You can't change an INSERT into a SELECT that produces a result set. Even if you try to inject a semicolon followed by a second SQL query, you just get sqlite3.Warning: You can only execute one statement at a time
Your first try above resulted in a syntax error because you had both a VALUES clause and a SELECT as a source for the data to insert. You can use either one but not both in SQL syntax. See https://www.sqlite.org/lang_insert.html
You probably already know how to make the code safe, so unsafe content cannot even cause a syntax error. But I'll include it for other readers:
curs.execute("INSERT INTO feedback VALUES (?)", (feedback,))
You can do it, for example to get table name
a' || (SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%'))-- -

inserting data in a mysql database via python

I'm trying to insert variables as data into a database
I'm using this (part of it)
query = "INSERT INTO table_name (name) VALUES (%S)"
aa="naam"
cursor.execute(query,aa)
and everytime, I get the following error message:
"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 '%S)' at line 1"
no matter what I try to do, I'm getting this message (put it in """, put () around it, ...)
Hope someone can help me
The format needs to be lowercase, so change the query into: query = "INSERT INTO table_name (name) VALUES (%s)".

MySQL query throwing 1064 error

I have a huge data which is stored in mysql db. One of the columns in the database is a long string. One of the strings is "iEdge detected the 'warning' condition 'iedge it" which is stored in string_type. I have to query the database and find how many such strings are there.I am querying from my python program. When I do it using something like
cur.execute("select count(*) from table1 as tmp where tmp.err_string='"+row[r]+"'")
row[r] contains "iEdge detected the 'warning' condition 'iedge it"
I am getting error 1064 (You have an error in your SQL syntax...). I think it is happening because of some quotes in the string. May I know how to fix this?
Can you try this:
sql = "select count(*) from table1 as tmp where tmp.err_string=%s"
cursor.execute(sql, [row[r]])
Let the MySQL Python library worry about escaping special characters and how to quote your string.
See this SO post for more information.

Error 1064 using mysql in python

I'm trying to use mysql 5.1 with python 2.6.6 and I'm getting the following error.
code :
query = "INSERT INTO present_list SET from='a', to='b'"
print query
cur.execute(query)
error :
Error 1064: 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 'from='a', to='b'' at line 1
Can somebody understand what is wrong ?
You need to use the backstroke in from and to like :
INSERT INTO present_list SET `from`='a', `to`='b
Since from is a keyword in mysql
Put a back strike before from. From is one of MySQL's reserved words
query = "INSERT INTO present_list (`from`, `to`) VALUES ('a', 'b')"
print query
cur.execute(query)
Please, learn SQL and Syntex then work on :
Your answer is:
For Insert Data into table
============================
query = "INSERT INTO present_list(from,to) values('a'.'b')";
print query
cur.execute(query)
For Update Data into table
============================
query = "Update present_list set from='a', to='b'";
print query
cur.execute(query)
from and to are mysql reserved words. So if you want to use them as normal names please use backtick(`) symbol around reserved word. For more info please goto
Select a column with a keyword name

Categories

Resources