Inserting through pymssql but no rows appear in the database

こ雲淡風輕ζ 提交于 2019-12-02 13:28:34

问题


Im quite new to python and im trying to write a script that puts values into a SQL database.

its a simple 2 column table that looks like this:

CREATE TABLE [dbo].[pythonInsertTest](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [value] [varchar](50) NULL

I tried doing a select query from python and that worked! So the connection or anything of that sort is not the problem. but when i'm inserting into the table with the following code:

import pymssql
conn = pymssql.connect(server='XXXX', user='XXXX', password='XXXX', database='XXXX')
cursor = conn.cursor()
cursor.execute("insert into pythonInsertTest(value) OUTPUT INSERTED.ID VALUES('test')")
row = cursor.fetchone()
while row:
    print "Inserted Product ID : " +str(row[0])
    row = cursor.fetchone()

the response is:

$? && exit 1
Inserted Product ID : 20
Exit status: 0

However if i look in my sql manager and select all the rows in said table, the row i just added is not in there... But when i manually insert a row trough an SQL query in the manager its added.

Thing to note that it did skip the ID the id that was "inserted" trough my python script.

Anyone seen this before or knows what to do?


回答1:


Ha, I've banged my head on this a few times as well. As far as I can tell, you are missing a commit statement. As per this example, add a conn.commit(), and hopefully you will be golden.



来源:https://stackoverflow.com/questions/32631805/inserting-through-pymssql-but-no-rows-appear-in-the-database

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