【问题标题】:pyodbc: multiple connection issues, DML statements in .ipynb files not reflected in SQL Serverpyodbc:多个连接问题,.ipynb 文件中的 DML 语句未反映在 SQL Server 中
【发布时间】:2019-11-06 23:34:31
【问题描述】:

我正在使用 pyodbc 连接到本地计算机上的数据库。我有两个 .ipynb 文件,它们分别负责填充该数据库中的两个关系。

我有两个令人不安的观察结果:

  1. 如果一个游标在一个文件中连接到我的数据库,而另一个游标在另一个文件中连接到数据库,则只有一个游标能够执行 DML 并从数据库中检索语句。

  2. 如果一个文件中的一个游标将元组插入到关系中,然后与数据库断开连接,然后另一个文件中的游标尝试从第一个游标更新的关系中检索信息,则不会信息被检索。这与在 SQL Server 中执行 select 语句相同。

以下是每个文件中发生的情况的概括:

文件1.ipynb:

    cursor.connect(...)
    cursor = conn.cursor()
    # big array of commands
    commands = ["insert into ... values ...", "insert into ... values ..."]

    for line in commands:
        cursor.execute(line)

打印出游标的内容,说明语句执行成功。

现在在 file2.ipynb 中:

    cursor.connect(...)
    cursor = conn.cursor()

    cursor.execute("select * from updatedTable") # this line hangs
    for row in cursor:
        print(row)        # if cursor is disconnected from file1, still nothing is printed 

任何帮助解决多个连接和确认数据的持久性将不胜感激。

更新:必须执行 cnxn.commit() 才能保留更改。

【问题讨论】:

    标签: sql-server pyodbc


    【解决方案1】:

    我不知道命令 cnxn.commit(),使用它后我已经实现了预期的行为。

    【讨论】:

    • 用答案更新您的问题。另请注意,您将使用 fast_executemany 获得更好的插入性能,并分批提交。您应该确认您的自动提交行为并确保处理批处理中的任何错误 crsr.fast_executemany = True crsr.executemany(sql, params)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多