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

时间:2014-04-23 15:25:06

标签: python sqlite

我刚开始学习SQLite。我用python。 问题是如何在表中创建行,以便它们按名称排列,以及如何使用(提取)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)')

感谢。

2 个答案:

答案 0 :(得分:1)

我认为你在创建表时遇到了一些问题。我怀疑它是否有效,因为名称列没有类型。它们可能应该是一些长度的varchar。 JOIN表定义也不对。

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应用程序运行时准备好表格。

如果这些仅仅是示例,我会更加难以理解您的表名。

答案 1 :(得分:0)

我在unique column problem.

上发现了唯一名称的问题

实际上,我应该将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")')