1

I am using pymssql in my django project to connect to a database. I'm trying to use execute() method to do an insert.
However I get this error:

Cannot insert the value NULL into column 'ID', table ITEMS

the ID column is primary key and so it should be filled by the sql itself as I understand. here is my insert command:

    bill_id = execute("""
       INSERT INTO ITEMS(COlUMN1,COlUMN2, COlUMN3,COlUMN4,COlUMN5)
       VALUES (%d, %d, %d, %d, %d);
        """, (1713, 6, 929, 1184, 25))

and none of these COLUMNs are ID. can anyone tell me what am doing wrong?

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Bahman Rouhani
  • 1,139
  • 2
  • 14
  • 33

1 Answers1

3

If id column is not an auto increment key column, it will not work. If you define a column in SQL within a create table statement it is not automatically an autoincrement column. You must define it. Perhaps you should make at first a query to get the max value of id column. At second you can increment the value und add the primary column to your insert statement.

I found this link to use django meta data api.

https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api

michaeldbjava
  • 114
  • 10
  • thanks, that's what I did eventually, but I still can't figure out why the id is not being set by sql. the column is auto increment so it should increment by itself. – Bahman Rouhani Oct 12 '17 at 09:54
  • Ok, it is an MySQL Database. – michaeldbjava Oct 12 '17 at 09:59
  • Try the following to show the structure of table. https://dev.mysql.com/doc/refman/5.7/en/show-columns.html – michaeldbjava Oct 12 '17 at 10:02
  • Ok, you use MS-SQL Server. The following shows you an possibility to show meta Data of table. At first analyse the structure. If you are 100% sure that it is an autoincrement column. I can not say which reason it has. https://stackoverflow.com/questions/3930338/sql-server-get-table-primary-key-using-sql-query. – michaeldbjava Oct 12 '17 at 10:19
  • thanks for your help. I appreciate it. I will try this as soon as possible – Bahman Rouhani Oct 12 '17 at 11:07