Python 如何在表中创建唯一的行?

Python 如何在表中创建唯一的行?,python,sqlite,Python,Sqlite,我刚开始学习SQLite。我使用python。 问题是如何在表中创建行,以便它们按名称是uniqe,以及如何使用(提取)id1和id2将它们插入到单独的表中 import sqlite3 conn = sqlite3.connect('my.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS table1( id1 integer primary key autoincrement, name)'''

我刚开始学习SQLite。我使用python。 问题是如何在表中创建行,以便它们按名称是uniqe,以及如何使用(提取)id1和id2将它们插入到单独的表中

import sqlite3

conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
          id1 integer primary key autoincrement, name)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
          id2 integer primary key autoincrement, name)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()


conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT INTO table2 VALUES (null, "The Invention of Wings")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
c.execute('INSERT INTO table1 VALUES (null, "Colleen Hoover")')
c.execute('INSERT INTO table2 VALUES (null, "Maybe Someday")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')

谢谢。

我想您在创建表时遇到了一些问题。我怀疑它是否有效,因为name列没有类型。它们应该是一些长度的varchar。联接表定义也不正确

CREATE TABLE IF NOT EXISTS table1 (
    id1 integer primary key autoincrement, 
    name varchar(80)
);

CREATE TABLE IF NOT EXISTS table2 (
    id2 integer primary key autoincrement, 
    name varchar(80)
);


CREATE TABLE IF NOT EXISTS t1_t2 (
    id1 integer,
    id2 integer,
    primary key(id1, id2),
    foreign key(id1) references table1(id1),
    foreign key(id2) references table2(id2) 
);
我不会用代码创建表。编写脚本,在SQLite管理中执行,并在Python应用程序运行时准备好这些表


如果表名不仅仅是示例,我会更加仔细地考虑这些表名。

我发现了表名唯一性的问题

实际上,我应该将INSERT改为INSERT或IGNORE

import sqlite3

conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
          id1 integer primary key autoincrement, name TEXT unique)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
          id2 integer primary key autoincrement, name TEXT unique)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()


conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT OR IGNORE INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT OR IGNORE INTO table2 VALUES (null, "The Invention of Wings")')

我们可以使用“name TEXT varchar(80)unique”作为列规范吗?我不知道;请查阅您的SQLite文档。你是否在问“独一无二”是否合适?这取决于你的要求。这将表明名称是一个候选键。是这样吗?是的,是这样。非常感谢。