【问题标题】:escape a single quote from a downloaded value sqlite3从下载的值 sqlite3 中转义单引号
【发布时间】:2016-03-29 20:17:29
【问题描述】:

我正在使用 python/selenium 和 sqlite3 将网页上的位置保存到 sqlite3 数据库。一些位置包含单引号

例如伦敦约翰巷的玛丽维尔

我知道在本地创建数据库时,我必须使用两个单引号来转义这个。约翰的车道。 REF:- questions/603572/how-to-properly-escape-a-single-quote-for-a-sqlite-database 抓取网站时如何实现。

我的代码如下:-

# get locations
locs = browser.find_elements_by_class_name("meta")
for loc in locs:
    if loc.text !="":
        print loc.text
        query += ",\'"+loc.text.replace(', ','-')+"\'"

我收到此错误是因为存在

cur.execute("INSERT INTO LOCATIONS VALUES("+query+");")
sqlite3.OperationalError: near "s": syntax error

我将完整地址保存到一个字段中。提前感谢您的帮助。

【问题讨论】:

标签: python sqlite


【解决方案1】:

您应该使用占位符而不是手动尝试转义您的数据。

conn = sqlite3.connect(':memory:')
conn.execute('create table locations (name text)')
locs = list(map("{}'s".format, range(100)))
conn.execute('insert into locations values ({})'.format(
    '), ('.join(['?'] * len(locs))  # Build your placeholders
), locs)
print(list(conn.execute('select * from locations limit 5')))

将打印

[("0's",), ("1's",), ("2's",), ("3's",), ("4's",)]

要执行的查询中的问号表示占位符,您的 DB-API(在本例中为sqlite3)将处理用您提供的数据替换那些。它还将处理所需的转义。

您还应该考虑使用executemany,因为手动为VALUES (?), (?), (?), ... 构建一个巨大的占位符列表会导致

sqlite3.OperationalError: too many terms in compound SELECT

这样做

conn.executemany('insert into locations values (?)', ((x,) for x in locs))

您可以插入数千行。

【讨论】:

  • 感谢您的详细解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
相关资源
最近更新 更多