【问题标题】:sqlite problem : sqlite3.OperationalError: near "where": syntax errorsqlite问题:sqlite3.OperationalError:“where”附近:语法错误
【发布时间】:2020-10-17 06:58:51
【问题描述】:

我正在尝试将我的爬虫中的数据插入到我的数据库中而不重复。

然而,

sqlite3.OperationalError:“where”附近:语法错误

c.execute('insert into stocks(stocknum) values (?) where not exists(select * from stocks)',(stock_num,))

上面是我要插入的代码。我确定“where”附近有问题,但我无法调试它。

【问题讨论】:

    标签: python sql sqlite select sql-insert


    【解决方案1】:

    如果我正确地关注了你,你想在stocknum 列中插入尚不存在的值。

    您的直接问题是您的查询不是有效的 SQLite 语法。您不能将values() 与where 子句一起使用,您需要使用select:

    insert into stocks(stocknum) 
    select ? 
    where not exists(select * from stocks)
    

    现在这是有效的 SQL,但不会执行您想要的操作。仅当stocks 完全为空时才插入。您需要将子查询与外部查询关联(这需要两次传递参数,或使用子查询):

    insert into stocks(stocknum) 
    select ?
    where not exists(select 1 from stocks where stocknum = ?)
    

    最后:如果您运行的是 SQLite 3.24 或更高版本,则使用on conflict clause 更容易实现。为此,您需要对列stocknum 设置唯一(或主键)约束。然后你可以这样做:

    insert into stocks(stocknum) 
    values (?)
    on conflict(stocknum) do nothing
    

    【讨论】:

      【解决方案2】:

      尝试添加IGNORE:

      c.execute('INSERT IGNORE INTO stocks(stocknum) values (?) where not exists(select * from stocks)',(stock_num,))
      

      【讨论】:

        【解决方案3】:

        我认为 %s 不是 ?。您可以找到文档 here

        query = 'insert into stocks(stocknum) values (%s) where not exists(select * from stocks)'
        args = (stock_num)
        
        c.execute(query,args)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-09
          • 1970-01-01
          相关资源
          最近更新 更多