我正在使用sqlite来组织用scraper脚本获取的数据,在执行“insert into”命令时遇到问题。在
作为一个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
将数据插入到表中,但我得到的是以下错误:
奇怪的是,列被创建但没有被填充。
当我使用.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语句中使用字符串格式(作为一个一般性的补充说明),因为出于安全目的,这是不好的做法:
https://www.w3schools.com/sql/sql_injection.asp
相关问题 更多 >
编程相关推荐