sqlite3.OperationalError - 尝试停止重复结果

时间:2017-08-02 20:42:36

标签: python sql python-3.x sqlite

我希望这段代码创建一个表,每次只打印一个列表而不是打印多个(从之前运行的结果)。我如何修复此代码,以便WHERE NOT EXISTS代码实际工作。

我遇到的错误是:

Traceback (most recent call last):
line 33, in <module>
data_entry()
line 14, in data_entry
c.execute("INSERT INTO myTestTable VALUES('James', 45, 'Home') WHERE NOT EXISTS (SELECT 1 FROM myTestTable WHERE name ='james' AND age =45 AND address ='school')") 
sqlite3.OperationalError: near "WHERE": syntax error 

代码:

import sqlite3 

conn = sqlite3.connect('dbtest.db') 

c = conn.cursor() 

param = "School" 


def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS myTestTable(name TEXT, age REAL, address TEXT)') 

def data_entry():
    c.execute("INSERT INTO myTestTable VALUES('James', 45, 'Home') WHERE NOT EXISTS (SELECT 1 FROM myTestTable WHERE name ='james' AND age =45 AND address ='school')")
    c.execute("INSERT INTO myTestTable VALUES('Jeff', 16, 'School') WHERE NOT EXISTS (SELECT 1 FROM myTestTable WHERE name ='james' AND age =45 AND address ='school')")
    c.execute("INSERT INTO myTestTable VALUES('Bob', 14, 'School') WHERE NOT EXISTS (SELECT 1 FROM myTestTable WHERE name ='james' AND age =45 AND address ='school')")
    c.execute("INSERT INTO myTestTable VALUES('Jack', 15, 'School') WHERE NOT EXISTS (SELECT 1 FROM myTestTable WHERE name ='james' AND age =45 AND address ='school')")
    conn.commit()

def query1():
    c.execute("SELECT * FROM myTestTable WHERE address = ?",(param,)) 
    while True:
        row=c.fetchone()
        if row == None:
            break
        print(row)

    c.close()
    conn.close()

create_table()

data_entry()

query1()

1 个答案:

答案 0 :(得分:0)

sqlite不支持插入语句的where子句。我相信您要做的是在表格中添加unique约束并使用insert or ignore

c.execute('CREATE TABLE IF NOT EXISTS myTestTable(name TEXT, age REAL, address TEXT, UNIQUE(name, age, address))') 

c.execute("INSERT OR IGNORE INTO myTestTable VALUES('James', 45, 'Home')")

详见下文:

这也是一个可扩展的解决方案,避免了@raganjosh指出的问题。但是,您可能希望以通知用户的方式处理重复。