gpt4 book ai didi

python - 如何修复 python sqlite 中的 'sqlite3.OperationalError: near "?": ' 错误?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:54 26 4
gpt4 key购买 nike

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

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

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

这是代码:

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 但我被困在这里了。

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

最佳答案

您有一个拼写错误:

c.execute("插入到 {} (?,?,?) 值 (?,?,?)".format(table),('Product_ID','Title',str(self. currDatePriceCloumnName),str(self.prodId),str(self.title),str(self.price)))

地址:

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

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

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

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

关于python - 如何修复 python sqlite 中的 'sqlite3.OperationalError: near "?": ' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com