SQLite3:Python输入到表 - 自动增量的麻烦

时间:2018-03-26 19:54:16

标签: python sql python-3.x sqlite

我目前在将数据导入sqlite3表时遇到问题。 在我的TEST计划中,用户在被要求输入时输入信息。 然后我把这个输入放在我的表中,但是,我遇到了AutoIncrementing" User ID"的问题。每个用户都有自己的ID,到目前为止有5个用户。当新用户输入他们的数据时,我该如何设置它以便自动设置" UserID"到下一个号码,在这种情况下为6。

如果我手动放入" 6"在第一个值(在下面的代码中),但我如何自动生成?

conn = sqlite3.connect('xxxxxxx.db')
c=conn.cursor()
NameCreate = input("Please enter your First and Last name: ")
UserNameCreate = input("Please enter your desired User Name: ")
PasswordCreate = input("Please enter your desired Password: ")
DOBCreate = input("Please enter your date of birth [DD.MM.YYYY]: ")
FavouriteArtistCreate = input("Please enter your favourite Arist: ")
FavouriteGenreCreate = input("Please enter your favourite Genre: ")

c.execute("INSERT INTO Users VALUES (AUTOINCREMENT, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')".format(NameCreate, DOBCreate, UserNameCreate, PasswordCreate, FavouriteArtistCreate, FavouriteGenreCreate))
conn.commit()

1 个答案:

答案 0 :(得分:2)

仅在数据库上显示您的操作是不够的。您需要显示数据库架构。

我们从sqlite doc发出两条警告:

  1. AUTOINCREMENT关键字会产生额外的CPU,内存,磁盘空间和磁盘I / O开销,如果不是严格需要,应该避免使用。通常不需要它。

  2. 在SQLite中,类型为INTEGER PRIMARY KEY的列是ROWID的别名(WITHOUT ROWID表除外),它始终是64位有符号整数。

  3. 除此之外,您的代码的问题是在表创建时指定自动增量,而不是插入时间。

    参见最小例子:

    import sqlite3
    
    conn = sqlite3.connect(':memory:')
    c = conn.cursor()
    c.execute("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
    
    NameCreate = 'a'
    c.execute("INSERT INTO users ('name') VALUES (?)", (NameCreate, ))
    conn.commit()
    print(c.execute('select * from users').fetchall())
    NameCreate = 'b'
    c.execute("INSERT INTO users ('name') VALUES (?)", (NameCreate, ))
    conn.commit()
    print(c.execute('select * from users').fetchall())
    

    请注意带有AUTOINCREMENT的CREATE TABLE行,尽管没有必要,因为sqlite3将在任何INTEGER PRIMARY KEY上执行AUTOINCREMENT。 因此,您需要将数据库迁移到表格中的新模式。

    在上面的示例中,没有迁移的错误手动解决方案可以如下(仅适用于权宜之计!):

    c.execute("INSERT INTO users ('id', 'name') VALUES ((SELECT MAX(id) + 1 FROM users), ?)", (NameCreate, ))