1

I'm using pypyodbc with SQL Server 2016.

I am trying to insert and grab the last id inserted into database following another user's remarks but the returned value seems to be encrypted. Is there a way to decrypt it?

def executeSQL (command):
    connection = pypyodbc.connect('Driver={SQL Native Client};'
                                    'Server=blah\blah;'
                                    'Database=Impact;'
                                    'uid=Admin;pwd=F$sfgdfgs99')
    cursor=connection.cursor()
    cursor.execute(command)
    id = cursor.execute("SELECT @@IDENTITY")
    connection.commit()
    connection.close()
    return id

sqlexecute = 'INSERT INTO PERSONS([LastName], [FirstName]) VALUES(\''+lastname.encode('utf-8')+'\',\''+firstname.encode('utf-8')+'\');\n'
lastid = executeSQL(sqlexecute)
print lastid

Output:

<pypyodbc.Cursor instance at 0x000000000B870C88>
Community
  • 1
  • 1
Jay
  • 741
  • 10
  • 26
  • A few notes in addition to the answer: you may want to alias `@@IDENTITY` - in fact, use `SCOPE_INDENTITY` for better scope accuracy. Try: `id = cursor.execute("SELECT SCOPE_IDENTITY() AS id")` Details on why you want to do this: https://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/ I'd also recommend using bound parameters for your `INSERT`: http://stackoverflow.com/questions/32748982/does-pyodbc-support-any-form-of-named-parameters – FlipperPA May 17 '17 at 10:46

1 Answers1

3

It is not encrypted, it is telling you the type of the object that this is an instance of. In this case, it is pypyodbc.Cursor.

To fetch the actual rows, you do id.fetchall() which will return a list of the results. You can then loop over them to read the contents.

Antimony
  • 2,230
  • 3
  • 28
  • 38