Почему получаю Too many values to unpack (expected 1) в своей функции?

Рейтинг: 0Ответов: 1Опубликовано: 02.08.2023

Есть функция:

import pyodbc

def foo (conn):
    try:

       str_error = ''
       conn.autocommit = True
       cursor = conn.cursor()
       cursor.execute("select 1")
    
     except Exception as error:
       print(error)
       str_error = str(error)
     finally:
       conn.autocommit = False
       cursor.close()
       return str_error

В качестве conn функция принимает соединение с sql-server полученное через pyodbc.connect(). Теперь когда пытаюсь вызвать функцию в своем коде:

error = foo(my_conn)

Получаю "too many values to unpack (expected 1)". При этом, вне функции запросы через то же соединение выполняются нормально. Как правильно вернуть строку из функции?

Ответы

▲ -1Принят

Мне помогла следующая конструкция:

 while cursor.nextset():
     pass

Сама функция выглядит так:

import pyodbc

def foo (conn):
    try:

       str_error = ''
       conn.autocommit = True
       cursor = conn.cursor()
       cursor.execute("select 1")

       while cursor.nextset():
            pass
    
     except Exception as error:
       print(error)
       str_error = str(error)
     finally:
       conn.autocommit = False
       cursor.close()
       return str_error

Хотя я думал, что execute метод не возвращает ничего, согласно документации он всегда возвращает сам cursor.

Поэтому и получал ошибку. cursor.nextset() же помогает пройтись по result sets безопасно.

This method will make the cursor skip to the next available result set, discarding any remaining rows from the current result set. If there are no more result sets, the method returns False. Otherwise, it returns a True and subsequent calls to the fetch methods will return rows from the next result set.

This method is primarily used if you have stored procedures that return multiple results.