【问题标题】:pyODBC and SQL Server 2008 and Python 3pyODBC 和 SQL Server 2008 和 Python 3
【发布时间】:2013-04-10 20:39:01
【问题描述】:

我已经为 Python 3.2 安装了 pyODBC,我正在尝试更新我作为测试创建的 SQL Server 2008 R2 数据库。

我在检索数据时没有问题,而且一直有效。

但是,当程序执行 cursor.execute("sql") 来插入或删除一行时,它不起作用 - 没有错误,什么都没有。响应就好像我成功更新了数据库但没有反映任何更改。

下面的代码本质上是创建一个字典(我稍后有这个计划)并且只是快速构建一个 sql insert 语句(它在我测试我写入日志的条目时起作用)

我的表中有 11 行 Killer,即使在提交之后也完全没有受到影响。

我知道这很愚蠢,但我看不到。

代码如下:

cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=PHX-500222;DATABASE=RoughRide;UID=sa;PWD=slayer')
cursor = cnxn.cursor()

# loop through dictionary and create insert entries
logging.debug("using test data to build sql")
for row in data_dictionary:
    entry = data_dictionary[row]
    inf = entry['Information']
    dt = entry['TheDateTime']
    stat = entry['TheStatus']
    flg = entry['Flagg']
    # create sql and set right back into row
    data_dictionary[row] = "INSERT INTO Killer(Information, TheDateTime, TheStatus, Flagg) VALUES ('%s', '%s', '%s', %d)"  % (inf, dt, stat, flg)

# insert some rows
logging.debug("inserting test data")
for row in data_dictionary.values():
    cursor.execute(row)

# delete a row
rowsdeleted = cursor.execute("DELETE FROM Killer WHERE Id > 1").rowcount
logging.debug("deleted: " + str(rowsdeleted))

cnxn.commit

【问题讨论】:

    标签: sql-server python-3.x odbc pyodbc


    【解决方案1】:

    假设这不是帖子中的错字,看起来您只是缺少 Connection.commit() 方法的括号:

    ...
    # delete a row
    rowsdeleted = cursor.execute("DELETE FROM Killer WHERE Id > 1").rowcount
    logging.debug("deleted: " + str(rowsdeleted))
    
    cnxn.commit()
    

    【讨论】:

    • 谢谢!!!!太有趣了,我正盯着我的问题——有趣的是,python 解析器没有警告或抱怨 cnxn.commit 不是属性而是函数。再次感谢!
    • @Tab 如果您通过脚本运行,则没有消息,但它会在解释器中打印对象的字符串表示形式
    • 此时我在 WingIDE 中运行 - .NET 是我的最后一个平台,所以这是一个相当大的转变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多