我在Python 3.3中使用pymssql
与我的Mssql db进行通信。我试图将元组中的用户数据保存到数据库中,但我不断收到这个奇怪的错误:
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")
我的方法,错误显示在最后一行:
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())
我怀疑它与编码和加密有关:
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
谁能告诉我这里做错了什么?以及如何解决它?
编辑: 我的查询现在看起来像这样:
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")
答案 0 :(得分:2)
使用绑定变量。它更安全,对DB更友好。
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
您的字符串将自动正确地包装在引号中。