【问题标题】:how to fix 'sqlite3.OperationalError: near "?": ' error in python sqlite?如何修复'sqlite3.OperationalError:靠近“?”:'python sqlite中的错误?
【发布时间】:2019-01-26 12:48:43
【问题描述】:

我正在使用 sqlite 来组织通过爬虫脚本获取的数据,在执行“插入”命令时遇到问题。

作为一名 Python 新手,我正在为一个电子网站制作爬虫。 我已经有了一个工作脚本,它会抓取所有页面,直到我决定修改代码以创建一个带有价格的新列并使用今天的日期命名该列。 现在由于某种原因,将数据插入表的 SQL 命令拒绝执行我添加的新列。

尝试使用 ? 将新列添加到 SQL 命令中方法和 .format() 方法没有成功。 在 ?s 和 {}s 周围尝试了各种 ' 位置。

这是代码:

class Product:
    def __init__(self, prodId, title, price=None):
        self.prodId = prodId
        self.title = title
        self.price = price
        self.currDatePriceCloumnName = date + 'Price'

    def insertToTable(self):
        self.addColumn()
        conn = sqlite3.connect(databaseName)
        c = conn.cursor()
        c.execute("insert into {} (?,?,?) values (?,?,?)".format(table),('Product_ID','Title',str(self.currDatePriceCloumnName),str(self.prodId),str(self.title),str(self.price)))
        conn.commit()
        conn.close()

    def addColumn(self):
        conn = sqlite3.connect(databaseName)
        c = conn.cursor()
        try:
            c.execute("alter table {} add column '?'".format(table),(str(self.currDatePriceCloumnName),))
            conn.commit()
            conn.close()
        except:
            pass

我希望 insertToTable 中的 c.execute 将数据插入到表中,但我得到的是这个错误:

  File "/home/sergio/Desktop/test/scraper.py", line 67, in insertToTable
    c.execute("insert into {} (?,?,?) values (?,?,?)".format(table),('Product_ID','Title',str(self.currDatePriceCloumnName),str(self.prodId),str(self.title),str(self.price)))
sqlite3.OperationalError: near "?": syntax error

奇怪的是该列已创建但未填充。 当我使用.format() 方法时,错误具有所需的列名而不是?,这告诉我问题可能与我使用self.currDatePriceCloumnName 的事实有关,但我从这里卡住了。

请帮忙.. 提前致谢! =]

【问题讨论】:

  • 表名和列名必须直接在语句中;你不能为它们使用参数,只能用于表达式中的值。
  • 感谢您的快速回复!那么调用 addColumn 时如何在数据库中创建列呢?也许我应该指定该列已创建但未填充。
  • 它实际上创建了一个具有所需名称而不是 ? 的新列? '?' 是带文字问号的字符串,不是参数。

标签: python sqlite


【解决方案1】:

你有一个错字:

c.execute("insert into {} (?,?,?) values (?,?,?)".format(table),('Product_ID','Title',str(self.currDatePriceCloumnName),str(self.prodId),str(self.title),str(self.price)))

在:

values (?,?,?)".format(table),

.format(table) 的结尾是您插入字符串的所有内容。额外的) 导致.format() 结束抛出语法错误,因为它不期望,。您没有传递任何其他值。

话虽如此,以后不要在 SQL 语句中使用字符串格式(作为一般附注),因为出于安全目的这是不好的做法:

https://www.w3schools.com/sql/sql_injection.asp

【讨论】:

  • 感谢您的回复!但这对我提出了几个问题,坦率地说,我不明白错字在哪里,我认为你说的是​​格式和?不会工作.. 但是self.addColumn() 在有问题的行实际创建列之前运行。 addColumninsertToTable 有何不同?我在这两个函数中使用相同的方法,而一个有效,另一个无效..
  • c.execute("insert into {} (?,?,?) values (?,?,?)".format(table), 将产生查询insert into tablename (?,?,?) values (?,?,?)。它不会在addColumn 中出错,因为c.execute("alter table {} add column '?'".format(table), 等于alter table tablename add column '?'。它实际上是在尝试添加一个名为“?”的列。 insertToTable 查询字符串正在寻找 4 个值,而不是一个。当您为.format() 加上一个结束) 时,除) 之外的任何其他内容都不会插入到字符串中。
猜你喜欢
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2021-05-11
  • 2019-02-07
  • 2020-02-06
  • 2019-01-12
相关资源
最近更新 更多