简体   繁体   中英

Flask Python sqlite3: primary key in table is null instead of int

When I input data into a table, I get null instead of int for the primary key. How can I fix this?

This is my table:

conn.execute('CREATE TABLE lists (listid INT PRIMARY KEY, book TEXT, chapter INT)')

I input data into lists with this code:

@app.route('/addbook', methods = ['POST', 'GET'])
def addbook():
    if request.method == 'POST':
        bt = request.form['bt']
        bc = request.form['bc']

        con =  sql.connect("seei.db")
        cur = con.cursor()

        cur.execute("INSERT INTO lists (book, chapter) VALUES (?, ?)", (bt, bc))

        con.commit()
        con.close()
        return render_template("addconcepts.html")

and this html:

<body>

<form action="{{ url_for('addbook') }}" method="POST">
  Book Title<br>
  <input type="text" name="bt" /><br>

  Book Chapter<br>
  <input type="text" name="bc" /><br>
  <input type="submit" name="submit">

</form>

</body>

From the SQLite documentation (emphasis mine):

With one exception noted below, if a rowid table has a primary key that consists of a single column and the declared type of that column is "INTEGER" in any mixture of upper and lower case, then the column becomes an alias for the rowid. Such a column is usually referred to as an "integer primary key". A PRIMARY KEY column only becomes an integer primary key if the declared type name is exactly "INTEGER". Other integer type names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED INTEGER" causes the primary key column to behave as an ordinary table column with integer affinity and a unique index, not as an alias for the rowid.

Create your table as:

CREATE TABLE lists (listid INTEGER PRIMARY KEY, book TEXT, chapter INT)

cur.execute("INSERT INTO lists (book, chapter) VALUES (?, ?)", (bt, bc))

This would produce a ProgrammingError for incorrect number of bindings. Instead use:

cur.execute("INSERT INTO lists (book, chapter) VALUES (?, ?)", [(bt, bc)])

Also, in your CREATE TABLE command, you would need to change INT to INTEGER for the autoincrement behavior.

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