简体   繁体   中英

Fetching a returned row of a query on MS SQL Server with sqlalchemy and pyodbc

I am trying to get the returned row from executing a row insertion. I tested the compiled sql directly on SQL Server, the query works fine and it returns a row correctly.

The problem is I am not able to get the returned row from the query. Here is my code and I am using pyodbc driver on Windows.

sql = """
    INSERT INTO mytable (id, name)
    OUTPUT Inserted.id, Inserted.name
    VALUES (...)
    """
result = db.execute(sql).fetchall()

This is the error I am getting:

ERROR:  Failed to save events: (Error) ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)') None None
Traceback (most recent call last):
  File "...\site-packages\sqlalchemy\engine\result.py", line 782, in fetchall
    l = self.process_rows(self._fetchall_impl())
  File "...\site-packages\sqlalchemy\engine\result.py", line 749, in _fetchall_impl
    return self.cursor.fetchall()
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')

Any idea? Thanks in advance!

You are not executing a query. You are writing to the database which should not return results. Instead, try the following:

# assuming db is your cursor
db.execute(sql) # inserts the data
result = db.execute('SELECT * FROM mytable').fetchall()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM