So I have the following statement
cursor.execute("UPDATE IllnessTable SET (?) = (?) WHERE IllnessName = (?)",
(self.SymptomName,self.IllnessStatus[ControlVar],CurrentIllnessName))
where self.SymptomName is a String, self.IllnessStatus[ControlVar] is an integer and CurrentIllnessName is a string. The variables exist and correspond directly to my table. I'm wondering what's wrong with this SQL statement itself as I just get:
sqlite3.OperationalError: near "(": syntax error
You can use the ? placeholder only for literals, not for identifiers such as column names. Use string formatting in your programming language to produce a SQL with the identifiers you want.
Also, enclosing the ? in parens is not necessary.
Therefore, change to something like:
cursor.execute("UPDATE IllnessTable SET {} = ? WHERE IllnessName = ?".format(self.SymptomName),
(self.IllnessStatus[ControlVar],CurrentIllnessName))
Related
I am new to working on Python. I m not able to understand how can I send the correct input t0 the query.
list_of_names = []
for country in country_name_list.keys():
list_of_names.append(getValueMethod(country))
sql_query = f"""SELECT * FROM table1
where name in (%s);"""
db_results = engine.execute(sql_query, list_of_names).fetchone()
Give the error " not all arguments converted during string formatting"
As implied by John Gordon's comment, the number of placeholders in the SQL statement should match the number of elements in the list. However SQLAlchemy 2.0+ no longer accepts raw SQL statements. A future-proof version of the code would be:
import sqlalchemy as sa
...
# SQL statements should be wrapped with text(), and should used
# the "named" parameter style.
sql_query = sa.text("""SELECT * FROM table1 where name in :names)"""
# Values should be dictionaries of lists of dictionaries,
values = {'names': list_of_names}
# Execute statements using a context manager.
with engine.connect() as conn:
db_results = conn.execute(sql_query, values).fetchone()
If I know right, there are a simpler solution. If you write curly bracets {}, not bracets (), and you place inside the bracets a variable, which contains the %s value, should work. I don't know, how sql works, but you should use one " each side, not three.
Sorry, I'm not english. From this, maybe I wasn't help with the question, because I don't understand correctly.
connection to postgresql database has been connected successfully.but while executing below query i am getting some kind of error which looks like :
column "e" of relation "analysis_result" does not exist
LINE 1: INSERT INTO analysis_result(user_id,E,A,C,N,O,total) VALUES ...
cursor = connection.cursor()
print("inside execution ")
cursor.execute("INSERT INTO analysis_result(user_id,E,A,C,N,O,total) VALUES (%s,%s,%s,%s,%s,%s,%s)",Result_lst)
i understand what is the error .i have to put each of E A C N O in quotes but while quoting them my sql query becomes invalid .Please give me a solution i am scraching my head for quite sometime now.
and Result_lst=[1,20,14,14,38,8]. Result_lst will be dyanamic values in integer forms.
If the column name contains upper case characters, you must surround it with double quotes, otherwise PostgreSQL will fold it to lower case (note the error message).
But you cannot simply use double quotes because that's what you used for the Python string.
Either use single quotes with the Python string:
cursor.execute('INSERT INTO analysis_result(user_id,"E","A","C","N","O",total) ...', Result_lst)
or escape the double quotes:
cursor.execute("INSERT INTO analysis_result(user_id,\"E\",\"A\",\"C\",\"N\",\"O\",total) ...", Result_lst)
In my Python code when I ask the user to input a string to SELECT, it works but when I try the UPDATE using the same input doesn't allow me to execute
Here is my code after the connection has been successfully done
curs = connection.cursor()
str_input1 = str(input("Input : "))
str_input2 = str(input("Input : "))
statement = "UPDATE table SET variable1 = "+str_input1+" WHERE name = "+str_input2
curs.execute(statement)
connection.commit
In theory this following code should work and update the variable, but instead I get the error at line curs.execute(statement) saying
cx_Oracle.DatabaseError: ORA-00904: John: invalid identifier
John was the str_input2 for where clause
Maybe its the format that was giving me an error but I'm not too sure.
Can someone point out what was the problem with my code?
The error is because you're not quoting the values. You'd get the exact same error from a SELECT statement.
These statements search for rows where the name column matches the string John:
SELECT * FROM table WHERE name = "John"
UPDATE table SET variable1 = "Hi" WHERE name = "John"
These statements search for rows where the name columns matches the John column—and if there is no John column, that's an error:
SELECT * FROM table WHERE name = John
UPDATE table SET variable1 = "Hi" WHERE name = John
So, you could fix this by just putting quotes around the values.
But you really, really, really shouldn't. This opens you up to SQL injection attacks, and stupid bugs where you don't quote or escape special characters properly, and performance problems where the database engine can't tell that you're running the same query over and over, and so on.
What you want to do is to use SQL parameters, instead of trying to format the string. I don't remember which parameter style cx_Oracle uses, but you can just import cx_Oracle; print(cx_Oracle.paramstyle), and look it up in the table to find out. And then do something like:
statement = "UPDATE table SET variable1 = :v WHERE name = :n"
curs.execute(statement, {'v': str_input1, 'n': str_input2})
Also, a few side notes:
connection.commit doesn't do anything; you're just referencing the commit method, not calling it. You need parentheses: connection.commit()
str(input()) is pointless. The input function always returns a string, so there's no reason to call str on it. (Unless you're using Python 2.x, in which case you should be using raw_input(), which returns a string, instead of using input to eval the string—opening up the same kinds of security problems as the SQL injection attack above—only to convert it back to a string.)
I'm trying to insert some values in a table, and although the rows are being created, the values aren't being recorded. Here is my code:
for i in range(2,6):
for team in ul[i]:
name = team.string #string from html element
print(name) #this works just fine, and prints the desired name
cur.execute("INSERT INTO teams (Name) VALUES(name)")
conn.commit()
Now if I put VALUES("Test String") instead, it works, 30 rows are added (what I want), and all with the Name: "Test String".
Yet when I put in my name variable, the rows are added as well, but the column values are empty. The column I'm putting the strings in is VARCHAR. Is there something I don't know about how the SQL statement is interpreted in the case of Python string variables?
It appears that the SQL statement is a simple string and he name variable isn't being inserted into it.
Perhaps you could do something like this:
sql = """INSERT INTO teams (Name) VALUES({0})""".format(json.dumps(name))
cur.execute(sql)
I use json.dumps(myVar) to escape special characters, e.g. quotes, etc... that might break the SQL insert statement.
Sometimes it's helpful to print out the SQL statement and try to run it in a client (e.g. MySQL Workbench), in order to see what changes, if any, are necessary to generate syntactically correct statements.
Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable.
code below:
cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s))
rows = cur.fetchall()
How do i manually insert double or single quotes around the value of s?
I've trying using str() and manually concatenating quotes around s but it still doesn't work.
The sql statement works fine iv double and triple check my sql query.
You shouldn't use Python's string functions to build the SQL statement. You run the risk of leaving an SQL injection vulnerability. You should do this instead:
cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s)
Note the comma.
Python will do this for you automatically, if you use the database API:
cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s)',s)
Using the DB API means that python will figure out whether to use quotes or not, and also means that you don't have to worry about SQL-injection attacks, in case your s variable happens to contain, say,
value'); drop database; '
If this were purely a string-handling question, the answer would be tojust put them in the string:
cur.execute('insert into tempPDBcode (PDBcode) values ("%s");' % (s))
That's the classic use case for why Python supports both kinds of quotes.
However as other answers & comments have pointed out, there are SQL-specific concerns that are relevant in this case.