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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top