如何使用 Python 在 SQLite 中正确设置列的 AUTO INCREMENT? [英] How to correctly set AUTO INCREMENT fo a column in SQLite, using Python?

查看:40
本文介绍了如何使用 Python 在 SQLite 中正确设置列的 AUTO INCREMENT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用以下代码:

I have been trying with the below code:

import sqlite3
data_person_name = [('Michael', 'Fox'),
                    ('Adam', 'Miller'),
                    ('Andrew', 'Peck'),
                    ('James', 'Shroyer'),
                    ('Eric', 'Burger')]
con = sqlite3.connect(":memory:")
c = con.cursor()
c.execute('''CREATE TABLE q1_person_name
             (name_id integer auto_increment primary key,
              first_name varchar(20) NOT NULL,
              last_name varchar(20) NOT NULL)''')
c.executemany('INSERT INTO q1_person_name VALUES (?,?,?)', data_person_name)
for row in c.execute('SELECT * FROM q1_person_name'):
    print row

有人可以帮助我使 name_id 自动递增吗?

Can somebody help me in making the name_id automatically incremented ?

推荐答案

在 SQLite 中,INTEGER PRIMARY KEY 列是自动递增的.还有一个 AUTOINCREMENT 关键字.在 INTEGER PRIMARY KEY AUTOINCREMENT 中使用时,一个使用略有不同的 Id 创建算法.

In SQLite, INTEGER PRIMARY KEY column is auto-incremented. There is also an AUTOINCREMENT keyword. When used in INTEGER PRIMARY KEY AUTOINCREMENT, a slightly different algorithm for Id creation is used.

#!/usr/bin/python

import sqlite3
data_person_name = [('Michael', 'Fox'),
                    ('Adam', 'Miller'),
                    ('Andrew', 'Peck'),
                    ('James', 'Shroyer'),
                    ('Eric', 'Burger')]

con = sqlite3.connect(":memory:")

with con:

    c = con.cursor()

    c.execute('''CREATE TABLE q1_person_name
                 (name_id INTEGER PRIMARY KEY,
                  first_name varchar(20) NOT NULL,
                  last_name varchar(20) NOT NULL)''')
    c.executemany('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person_name)

    for row in c.execute('SELECT * FROM q1_person_name'):
        print(row)

此代码现在可以正常工作了.

This code now works OK.

c.executemany('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person_name)

当使用自增时,我们必须明确说明列名,省略一种自动递增的.

When using auto-increment, we have to explicitly state the column names, omitting the one that is auto-incremented.

$ ./test.py 
(1, u'Michael', u'Fox')
(2, u'Adam', u'Miller')
(3, u'Andrew', u'Peck')
(4, u'James', u'Shroyer')
(5, u'Eric', u'Burger')

这是代码示例的输出.

这篇关于如何使用 Python 在 SQLite 中正确设置列的 AUTO INCREMENT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆