I can't insert data into database using a dynamic query in python script
def execute_query(self, qo):
query_string = "INSERT INTO " +dep_table+ " (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES (%s, %s, %s, %s, %s, %s, %s)" % ("'CO'","'"+qo.db_src+"'","'"+qo.table_src+"'","'"+qo.table_des+"'","'"+qo.check_func+"'","'"+qo.table_des+"'","'NULL'")+";"
cursor.execute(query_string)
I got this error:
ERROR: Failed to set dependencies informations : ORA-00933: SQL command not properly ended
The connection to the database is okay, but I can't insert.
Drop the semi-colon at the end of the string you are creating / executing.
It shouldn't be part of the SQL statement, rather used in some client tools to indicate the end of a statement so that the client can send it to the database to be executed.
I found the solution to the problem
connection.commit()
You can use format method in Python like below:
def execute_query(self, qo):
query_string = "INSERT INTO {0} (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7})".format(dep_table, 'CO', qo.db_src, qo.table_src, qo.table_des, qo.check_func, qo.table_des, 'NULL')
cursor.execute(query_string)
Related
I have an issue trying to upload files from Python to my database. I can insert the binary data into the table just fine using %s, but when I try to update the record, I am unable to get this to work. Am I doing something wrong?
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 '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x90\x00\x00\x00\xc8\x08\x06\x00\' at line 8
Now, I know this is because the bytestring contains a ' so this doesn't work, it excepts, and leaves some security holes open if it were to work:
dbc.execute(f"""UPDATE userdata SET
emailaddr ='{email}',
firstname ='{namee}',
lastname ='{laste}',
username ='{usere}',
password ='{passe}',
phonenum ='{phone}',
photoimg ='{u_pho}'
WHERE user_id = '{user_ident}';""")
but I'm wondering if I can update a value like this:
insertcommand = f"""UPDATE userdata SET (emailaddr,firstname,lastname,username,password,phonenum,photoimg) VALUES (%s, %s, %s, %s, %s, %s, %s) WHERE user_id = '{user_ident}'"""
insertrecord = email,namee,laste,usere,passe,phone,u_pho
dbc.execute(insertcommand,insertrecord)
How would I go about updating bytestrings in MySQL with Python?
I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))
I am trying to execute an sql statement that should add some data to a database like so:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( db.escape_string(self.imdbID), self.name))
I have also tried:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( self.imdbID, self.name))
But i keep getting this error regardless of using the escape_string or not. See below:
MySQLdb._exceptions.ProgrammingError: (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 '/name/nm0991810, Mahershala Ali)' at line 1")
I am pretty sure it has to do with the forward slash but i cant get it to work. How do i fix this issue?
If any more information is needed let me know!
Do this instead:
query = "INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)"
cursor.execute(query, (self.imdbID, self.name))
If I am not mistaken mysqldb takes care of this for you.
Otherwise you can do:
cursor.execute(query, (db.escape_string(self.imdbID), self.name))
I'm using Angular, Flask and MySQL.connector to connect to a MySQL database:
This is my python flask code handling post requests inserting a new "movie":
#app.route("/addMovies", methods=['POST'])
def addMovies():
cnx = mysql.connector.connect(user='root', database='MovieTheatre')
cursor = cnx.cursor()
insert_stmt = (
"INSERT INTO Movie (idMovie, MovieName, MovieYear) "
"VALUES (%d, %s, %d)"
)
post = request.get_json()
#data = (post['idMovie'], post['MovieName'], post['MovieYear'])
data = (100, 'Test', 2010) # test data
print(insert_stmt,data)
cursor.execute(insert_stmt,data)
cnx.commit()
cnx.close()
return data
I know its not my Angularjs, because my browser console says Internal Server Error (500) so I started printing out the insert statement handled by flask and mysql.connector:
('INSERT INTO Movie (idMovie, MovieName, MovieYear) VALUES (%d, %s, %d)', (100, 'Test', 2010))
Which seems correct.
However I keep getting
"Wrong number of arguments during string formatting")
ProgrammingError: Wrong number of arguments during string formatting
===============================================================================
Thanks to the answers, its fixed, for those wondering this is what I switched my code to :
#app.route("/addMovies", methods=['POST'])
def addMovies():
cnx = mysql.connector.connect(user='root', database='MovieTheatre')
cursor = cnx.cursor()
insert_stmt = (
"INSERT INTO Movie (idMovie, MovieName, MovieYear) "
"VALUES (%s, %s, %s)"
)
post = request.get_json()
data = (post['idMovie'], post['MovieName'], post['MovieYear'])
print(insert_stmt,data)
cursor.execute(insert_stmt,data)
cnx.commit()
cnx.close()
return data
Check the docs, it says the cursor.execute() method converts things as necessary to something the database understands. It seems you are supposed to use only %s placeholders in your string and let everything else on the execute method.
SQL parameter substitution is not the same as string formatting. You should always use %s, even for integers.
I am trying to insert some data into a database using the variable test as the table name. But unfortunately I cant seem to achieve this. Can anyone help me out?
From my raise I am getting:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
My code:
test = "hello"
# Open database connection
db = MySQLdb.connect("127.0.0.1","admin","password","table" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()
# disconnect from server
db.close()
I don't think MySQLdb lets you use parameters for table names -- usually this is used for actual parameters (ones that are sometimes from user input and need sanitization - the name/age/gender part gets this right). You could use Python's string formats to achieve this:
sql = ("""INSERT INTO {table} (name, age, gender)
VALUES (%s, %s, %s)""".format(table=table), (test))
Something like this will work:
sql = """INSERT INTO %s (name, age, gender)
VALUES (%s, %s, %s)""" % (test, "%s", "%s", "%s")
You need to separate Python's string substitution from MySQL's parameter substitution. The above is a crude approach, but minimally different from your own code.