简体   繁体   中英

Python pyODBC : Issue inserting into a sql server table with an identity column

An INSERT statement that was created with Python gives me an error when I execute and commit it. I have taken a copy of the statement from Python and run it myself in SQL SERVER and it works fine there. The table I am trying to insert into has an identity column. When Python trys to execute it will give me an error saying what is below when I exclude the identity column in the statement

Table looks like this MY_TABLE ( ID INT IDENTITY(1,1) NOT NULL, A INT, B INT)

INSERT INTO MY_TABLE (A, B) VALUES(VALUE_A, VALUE_B);

"('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'MY_IDENTITY_COLUMN', table 'MY_TABLE'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")"

But when I try to include the value for the Identity column (I don't want to do this) I get the following error which makes sense as it's an identity column that we let the table auto-increment

"Cannot insert explicit value for identity column in table 'MY_TABLE' when IDENTITY_INSERT is set to OFF."

When I run the query in SQL SERVER the table fills the value for the Identity Column itself and auto-increments but for some reason when I run the statement in Python it does not do this and tries to pass a NULL

SQL SERVER version: 10.50.6560.0

A little hard to tell without your code, but here is an example.

In database create a test table

CREATE TABLE dbo.test(  
ID INT IDENTITY NOT NULL PRIMARY KEY,   
Name VARCHAR(40) NOT NULL  
);  

Then in Python specify the columns you are inserting into

import pyodbc

warecn = pyodbc.connect("Your Connection Stuff")

Inscursor = warecn.cursor()

Inscursor.execute("Insert into dbo.test(name) values ('This'), ('is'), ('a'), ('test')")


Inscursor.commit()
Inscursor.close()
del Inscursor
warecn.close()

Recognising it's a little late but... I had the same problem recently using some old program and ODBC. The solution was to create a View in SQL Server with only the columns required (ie A and B in your case) and then insert into that View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM