[Python] SQLite3 primary key not auto incrementing

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I tried writing this code hoping that it will auto increment, but somehow it is not working and the output entries in id column are set to 'None'.I have also tried other answers but none of them are working.Please help if possible.

    Here is the code:

    import sqlite3

    def connect():
    conn=sqlite3.connect("books.db")
    cur=conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year int,isbn int)")
    conn.commit()
    conn.close()

    def insert(title,author,year,isbn):
    conn=sqlite3.connect("books.db")
    cur=conn.cursor()
    cur.execute("INSERT INTO book VALUES (?,?,?,?)",(title,author,year,isbn))
    conn.commit()
    conn.close()

    def view():
    conn=sqlite3.connect("books.db")
    cur=conn.cursor()
    cur.execute("SELECT * FROM book ")
    rows=cur.fetchall()
    conn.close()
    return rows

    connect()
    insert("sample","abc",2003,123456)
    insert("sample2","def",2003,123457)
    print(view())


    This is the output:

    [(None, 'sample', 'abc', 2003, 123456), (None, 'sample2', 'def', 2003, 123457)]

    Continue reading...

Compartilhe esta Página