I am using pymssql in Python 3.3 to communicate with my Mssql db. And I am trying to save the data from a user in a tuple to the database, but I keep getting this weird error:
pymssql.ProgrammingError: (102, b"Incorrect syntax near '\\'.DB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
My method, the error is showing in the last line:
user.password = user.password.encode('utf_8')
user.password = encrypt_RSA(user.password)
cursor.execute('INSERT INTO Usertable VALUES(%i, \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')' % user.get_usertuple())
I suspect it has something to do with the encoding and encrypting:
def encrypt_RSA(message, public_key_loc = "pubkey.pem"):
'''
param: public_key_loc Path to public key
param: message String to be encrypted
return encoded encrypted string
'''
key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(key)
rsakey = PKCS1_OAEP.new(rsakey)
encrypted = rsakey.encrypt(message)
return encrypted
Can anyone tell what I am doing wrong here? And how to fix it?
EDIT:
My query now looks like this:
cursor.execute('INSERT INTO Usertable VALUES(%i, %s, %s, %s, %s, %s, %s)' % user.get_usertuple())
But that gives me another error: pymssql.OperationalError: (103, b"The identifier that starts with (LONG TEXT) is too long. Maximum length is 128.DB-Lib error message 103, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
use bind variables. it is safer, it is kinder to the DB.
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
your strings will be automatically and properly wrapped in quotes.
Related
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)
I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s")
cursor.execute(query, (info, shipDate, warranty, name, sn, ))
conn.commit()
Error:
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 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.
No , before the WHERE statement
My output works in csv, but not when trying to insert it into mysql. I get the following error and have not been able to figure it out. I'm a novice so I may be missing something obvious. Same error in Python 2x and 3x.
pymysql.err.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 'key, title, content, start_date, end_date, initial_update) VALUES('reddit', 'h' at line 1")
mainDB_cnx = pymysql.connect(user='XXXX', password='XXXX',
host='XXXX',
database='Test', use_unicode=True, charset="utf8mb4")
with mainDB_cnx:
mainDB_cursor = mainDB_cnx.cursor()
mainDB_cursor.execute(
"INSERT INTO reddit(site, site_url, key, title, content, start_date, end_date, initial_update) VALUES(%s, %s, %s, %s, %s, STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'))",
(["reddit", "http://www.reddit.com", url, title, content, datetime.strptime(date,'%d %B %Y').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d')]))
print("Successful")
KEY is a reserved word in the MySQL dialect of structured query language. See this. https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-K
So you must wrap that column name in delimiters whenever you mention it.
Try
INSERT INTO reddit (side, site_url, `key`, title, ....
Or, better, don't use reserved words for the names of columns in your tables. The next programmer to work on your system will thank you.
I have the following sample Python code, and when I try to execute, am getting mysql error message. Context, am trying to create custom logs, log the messages, insert to a MySql table for analysis. Providing relevant portions for mysql execute.
levelnum= str(record.levelno) # 40
levelname=str(record.levelname) # ERROR
msg=str(self.log_msg) # "This error occurred: This is test message"
createtime=str(tm) #2018-06-26 03:43:47
record.name = 'MY_LOGGER'
sql = 'INSERT INTO emp.log (log_level, log_levelname, log, created_at, created_by) VALUES ('+levelnum+ ', '+levelname+ ', '+msg+ ', '+createtime+ ', '+record.name+')'
Error message: ProgrammingError: (1064, u"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 'error msg, 2018-06-26 03:43:47, MY_LOGGER)' at line 1")
Am using mysql, and trying to insert to the table as follows:
try:
self.sql_cursor.execute(sql)
self.sql_conn.commit()
except pymysql.InternalError as e:
print e
print 'CRITICAL DB ERROR! Logging to database not possible!'
I think, am missing some formatting while passing parameters in the SQL query, but couldn't get the correct one.
Appreciate if someone can help fix this.
You are not quoting the timestamp, hence the error.
Rather than trying to quote the values manually, use the built-in quoting functionality provided by pymysql as part of the DBI interface.
sql = 'INSERT INTO `emp.log` (`log_level`, `log_levelname`, `log`, `created_at`, `created_by`) VALUES (%s, %s, %s, %s, %s)'
self.cursor.execute(sql, (levelnum, levelname, msg, createtime, record.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.