pyODBC and SQL Server 2008 and Python 3

倖福魔咒の 提交于 2019-12-21 23:13:58

问题


I have pyODBC installed for Python 3.2 and I am attempting to update a SQL Server 2008 R2 database that I created as a test.

I have no problem retrieving data and that has always worked.

However when the program performs a cursor.execute("sql") to insert or delete a row then it does not work - no error, nothing. The response is as if I am successful updating the database but no changes are reflected.

The code below essentially is creating a dictionary (I have plans for this later) and just doing a quick build of a sql insert statement (which works as I testing the entry I wrote to the log)

I have 11 rows in my table, Killer, which is not being affected at all, even after a commit.

I know this is something dumb but I can't see it.

Here is the code:

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

回答1:


Assuming this isn't a typo in the post, looks like you're just missing parentheses for the Connection.commit() method:

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

cnxn.commit()


来源:https://stackoverflow.com/questions/15935933/pyodbc-and-sql-server-2008-and-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!