无法将元组插入到mssql数据库
我在用 pymssql
这个库和我的 Mssql 数据库进行沟通,使用的是 Python 3.3。我想把用户的数据保存到数据库里,这些数据是以元组的形式存储的,但我总是遇到一个奇怪的错误:
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")
1 个回答
3
使用绑定变量。这种做法更安全,对数据库也更友好。
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
你的字符串会自动并正确地用引号包裹起来。