Python和sqlite3抛出一个错误:sqlite3.OperationalError:附近的“s”:语法错误

问题描述:

我试图使用Python和BeautifulSoup来抓取一些Web信息,通过它迭代,然后插入一些片段到sqlite3数据库。但我一直想出这个错误:Python和sqlite3抛出一个错误:sqlite3.OperationalError:附近的“s”:语法错误

文件 “/Users/Chris/Desktop/BS4/TBTfile.py”,线路103,在TBTscrape c.execute(项目) sqlite3.OperationalError:近 “S” :语法错误

对于非常类似的刮板,此相同的代码工作正常,不会抛出这些错误。以下是其中的一部分:

listicle.append("INSERT INTO headlines (heds, url, image_loc, time, source) VALUES ('" + TBTheadline + "', '" + TBTurl + "', '" + imageName + "', '" + TBTpostDate + "', '" + source + "')") 

    else: 
     print "TBT item already in database" 

print listicle 

for item in listicle: 
    c.execute(item) 
    conn.commit() 
    row = c.fetchall() 
    print "This has been inserted succcessfully: ", item 

您将所收集的数据连接到您的SQL语句中。 从来没有这样做,它是mother of all anti-patterns。除了你正在看到的问题(可能是由于刮掉的HTML中的'或类似的字符),你的代码中有一个巨大的安全漏洞(在你的情况下可能并不重要)。

无论如何,sqlite3有一个很好的方式做你想要的:executemany。在你的情况下,

listicle.append((TBTheadline,TBTurl,imageName,TBTpostDate,source)) 

conn.executemany("INSERT INTO headlines (heds, url, image_loc, time, source) VALUES (?,?,?,?,?)", listicle) 
+0

哇,这太容易了。我还没有遇到过。美丽,谢谢! – Chris