Sqlite operate错误:IF NOT EXISTS的语法

时间:2014-04-05 14:59:56

标签: python sql sqlite python-2.7

我收到此代码的sql lite操作语法错误:

def checkIn(uname, title):
   bookid = findBookID(title) #returns an int bookid given the title
   print bookid
   with libDB:
      checkCur = libDB.cursor()
      checkCur.execute(
         "IF NOT EXISTS(SELECT 1 FROM Checks WHERE Username =? AND bookID =?) INSERT INTO Checks VALUES(?,?)",
         (uname, bookid, uname, bookid))
      checkCur.close()
      mess = "OK::CHKIN::", uname, "::", title
      return mess 

错误是:

  sqlite3.OperationalError: near "IF": syntax error

这是我定义表格的方式:

   with libDB:
     checkCur = libDB.cursor()
     checkCur.execute(
         "CREATE TABLE Checks(bookID INTEGER, Username TEXT, FOREIGN KEY(bookID) REFERENCES Books(bookID),FOREIGN KEY(Username) REFERENCES Users(Username))")
     checkCur.close()

如果我遗漏了一些简单的话,我道歉。我多次查看代码并在线搜索,我不知道语法错误在哪里。我将我的查询与我在网上找到的查询进行了比较,看起来很匹配。我能想到的唯一可能是错误的是,如果我的参数不正确但我尝试改变它们,我仍然无法让它发挥作用。

提前感谢您的帮助。

-CJ

1 个答案:

答案 0 :(得分:2)

IF NOT EXISTS与sqlite不兼容。您想要的插入语句如下:

INSERT INTO Checks (bookID, Username)
  SELECT 7, 'Bob'  /* for example */
    WHERE NOT EXISTS (SELECT 1 FROM Checks WHERE bookID = 7 and Username = 'Bob');

请注意,NOT EXISTS符号位于WHERE子句中。这种插入语句是compatible with sqlite。您可以使用sql fiddle here

所以在你的Python函数中,请尝试这样做:

insert_stmt = ("INSERT INTO Checks (bookID, Username) "  # note the space at end of string
                  "SELECT ?, ? "
                  "WHERE NOT EXISTS (SELECT 1 FROM Checks WHERE bookID = ? and Username = ?)")
checkCur.execute(insert_stmt, (bookid, uname) * 2)  # no need to repeat the bookid, uname combo twice; just multiply the tuple by 2