【发布时间】: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 时如何在数据库中创建列呢?也许我应该指定该列已创建但未填充。
-
它实际上创建了一个具有所需名称而不是
?的新列?'?'是带文字问号的字符串,不是参数。