pyODBC 和 SQL Server 2008 和 Python 3

Tab*_*Tab 2 sql-server odbc pyodbc python-3.x

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

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

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

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

我的表 Killer 中有 11 行,即使在提交后也不受影响。

我知道这是愚蠢的,但我看不到它。

这是代码:

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
Run Code Online (Sandbox Code Playgroud)

Bry*_*yan 7

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

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

cnxn.commit()
Run Code Online (Sandbox Code Playgroud)