Repository: langchain
Issue: Trying to use SQLDatabaseLoader gives error
Labels: 🤖:bug,investigate

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I am sure that this is a bug in LangChain rather than my code.
- [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).

### Example Code

    def  initialise(self):       
        print("initialising...")
        
        connect_Url = URL.create(
            drivername="mssql+pyodbc",
            username=ConfigSettings.userId,
            password=ConfigSettings.password,
            host=ConfigSettings.server,
            database=ConfigSettings.database,
            query={"driver": "ODBC Driver 17 for SQL Server"},
        )
        
        engine = create_engine(connect_Url,echo=False)
        con = engine.connect()
               
        #self.db = SQLDatabase(engine=engine)
        self.db = SQLDatabase.from_uri(connect_Url, include_tables=["TestTable"], sample_rows_in_table_info=2)
        
        #table_names = self.db.get_usable_table_names()
        #print("Number of tables: ", len(table_names))
        
        #response = self.db.run("SELECT top 10 * FROM InvoiceStatus")
        #print(response)
               
        query = "SELECT top 10 * FROM TestTable"
        
        self.llm = OpenAI(api_key=OPENAI_API_KEY)
        
        databaseLoader = SQLDatabaseLoader(db=self.db,query=query)
        docs = databaseLoader.load()
        print("Number of documents: ", len(docs))
        
        print("Exiting...\n\n")

### Error Message and Stack Trace (if applicable)

    def  initialise(self):       
        print("initialising...")
        
        connect_Url = URL.create(
            drivername="mssql+pyodbc",
            username=ConfigSettings.userId,
            password=ConfigSettings.password,
            host=ConfigSettings.server,
            database=ConfigSettings.database,
            query={"driver": "ODBC Driver 17 for SQL Server"},
        )
        
        engine = create_engine(connect_Url,echo=False)
        con = engine.connect()
               
        #self.db = SQLDatabase(engine=engine)
        self.db = SQLDatabase.from_uri(connect_Url, include_tables=["TestTable"], sample_rows_in_table_info=2)
        
        #table_names = self.db.get_usable_table_names()
        #print("Number of tables: ", len(table_names))
        
        #response = self.db.run("SELECT top 10 * FROM InvoiceStatus")
        #print(response)
               
        query = "SELECT top 10 * FROM TestTable"
        
        self.llm = OpenAI(api_key=OPENAI_API_KEY)
        
        databaseLoader = SQLDatabaseLoader(db=self.db,query=query)
        docs = databaseLoader.load()
        print("Number of documents: ", len(docs))
        
        print("Exiting...\n\n")

### Description

Hi there, 

I'm new here so apologies if its a silly question.

I'm trying to query the database using the **SQLDatabaseLoader** but getting an error when calling load().

**sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLFetch)')**

If I do any arbitrary SQL query, it works fine e.g

#response = self.db.run("SELECT top 10 * FROM InvoiceStatus")
#print(response)

I tried different versions of SQLAlchemy with no luck either..

However, when calling load() it gives the following error:

----------------- RAG Db With OpenAI ----------------
initialising...
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\cursor.py", line 1109, in fetchone
    row = dbapi_cursor.fetchone()
          ^^^^^^^^^^^^^^^^^^^^^^^
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLFetch)')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:\Projects\Python\main.py", line 28, in <module>
    dbRag1.initialise()
  File "E:\Projects\Python\ragWithOpenAI_Database.py", line 82, in initialise
    docs = databaseLoader.load()
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\langchain_core\document_loaders\base.py", line 31, in load
    return list(self.lazy_load())
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\langchain_community\document_loaders\sql_database.py", line 90, in lazy_load
    for i, row in enumerate(result.mappings()):
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\result.py", line 508, in iterrows
    for raw_row in self._fetchiter_impl():
                   ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\cursor.py", line 2086, in _fetchiter_impl
    row = fetchone(self, self.cursor)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\cursor.py", line 1114, in fetchone
    self.handle_exception(result, dbapi_cursor, e)
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\cursor.py", line 1085, in handle_exception
    result.connection._handle_dbapi_exception(
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 2325, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\cursor.py", line 1109, in fetchone
    row = dbapi_cursor.fetchone()
          ^^^^^^^^^^^^^^^^^^^^^^^
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLFetch)')

Any help would be greatly appreciated.

Thank you all,

J

### System Info

System Information
------------------
> OS:  Windows
> OS Version:  10.0.22631
> Python Version:  3.12.7 (tags/v3.12.7:0b05ead, Oct  1 2024, 03:06:41) [MSC v.1941 64 bit (AMD64)]

Package Information
-------------------
> langchain_core: 0.3.21
> langchain: 0.3.8
> langchain_community: 0.3.8
> langsmith: 0.1.146
> langchain_experimental: 0.3.3
> langchain_text_splitters: 0.3.2

Optional packages not installed
-------------------------------
> langserve

Other Dependencies
------------------
> aiohttp: 3.10.10
> async-timeout: Installed. No version info available.
> dataclasses-json: 0.6.7
> httpx: 0.27.2
> httpx-sse: 0.4.0
> jsonpatch: 1.33
> numpy: 1.26.4
> orjson: 3.10.11
> packaging: 24.1
> pydantic: 2.9.2
> pydantic-settings: 2.6.1
> PyYAML: 6.0.2
> requests: 2.32.3
> requests-toolbelt: 1.0.0
> SQLAlchemy: 2.0.0
> tenacity: 8.5.0