首页 > 解决方案 > 如何修复'sqlite3.OperationalError:靠近“?”:'python sqlite中的错误?

问题描述

我正在使用 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

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

  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但我从这里被卡住了。

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

标签: pythonsqlite

解决方案


你有一个错字:

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


推荐阅读