pyODBC and SQL Server 2008 and Python 3

2020-07-26 15:47发布

问题:

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()