python - 如何修复'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.execute
ininsertToTable
将数据插入表中,但我得到的是这个错误:
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("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 语句中使用字符串格式(作为一般附注),因为出于安全目的这是不好的做法:
推荐阅读
- c# - ASP.NET Framework v4 App using OpenIDConnect and Session[] variables will not authenticate the second session
- python - How to store a numpy.ndarray into MySQL?
- c# - 在 C# 中按两个属性对 JSON 数据进行分组
- java - URL truncated when it contains semicolons
- android - ListView - 使按钮 onClick 事件将值添加到同一行的 EditText
- python - Raspberry Pi 3:OpenCV 3.4.0 安装后缺少一些文件,无法在我的代码中调用
- javascript - 将字母分配给特定范围内的数值
- ldap - LDAP err32 on Jetty JAAS setting with Openldap
- linux - How to Do a For Loop Instead of a While Loop in Shell Scripting
- c - 将 execvp 与输入文件一起使用到程序并将输出重定向到新文件