Python “保护”;请求
我有这样一个sql请求:Python “保护”;请求,python,sql,sqlite,Python,Sql,Sqlite,我有这样一个sql请求: "INSERT INTO pirate(title, title_simple, user, magnet_link, \ url, created, size, infos, images, description, number, response, new) VALUES (\"{0}\", \"{1}\", \"{2}\", \"{3}\", \ \"{4}\", \"{5}\", \"{6}\", \"{7}\", \"{8}\", \"{9}\",
"INSERT INTO pirate(title, title_simple, user, magnet_link, \
url, created, size, infos, images, description, number, response, new) VALUES
(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \
\"{4}\", \"{5}\", \"{6}\", \"{7}\", \"{8}\", \"{9}\", \"{10}\", \"{11}\", \"{12}\")".format(blablabla...)
但我的查询的一些参数是巨大的文本片段,大部分类似于描述。有时文本中有这样一个字符:“
我已经尝试保护我在查询中使用的字符串,例如以下语法:
\"{9}\"
但它不适用于“
。你知道如何解决我的基本问题吗?好的方法是什么
编辑:
@Martijn Pieters:我试过了,但没用:
requete = "INSERT INTO pirate(title, title_simple, user, magnet_link, \
url, created, size, infos, images, description, number, response, new) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
params = (torrent.title, simpleChar(torrent.title), torrent.user, torrent.magnet_link,
str(torrent.url), torrent.created, strByteToOctet(torrent.size)[1],
str_infos, str_images, torrent.info, torrent.id, retours, True)
bdd = sqlite3.connect("fichiers.sqlite")
bdd.row_factory = sqlite3.Row
c = bdd.cursor()
c.execute(requete, params)
bdd.commit()
c.close()
bdd.close()
而且,我是在线程中执行此操作的,因此我无法轻松地调试信息将值的转义留给数据库适配器。改为使用SQL参数,而不是字符串格式:
query = """\
INSERT INTO pirate(
title, title_simple, user, magnet_link,
url, created, size, infos, images, description, number, response, new)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
params = (pirate_title, simplify(pirate_title), userid, link, url,
datetime.now(), 0, torrent_infos, torrent_images, desc,
42, response, True)
cursor.execute(query, params)
使用SQL参数可以将转义委托给专家,防止SQL注入攻击,并允许数据库缓存和重用它生成的任何查询计划
见:
通常,SQL操作需要使用Python变量中的值。您不应该使用Python的字符串操作来组装查询,因为这样做是不安全的;它使您的程序容易受到SQL注入攻击(有关可能出错的幽默示例,请参阅)
相反,使用DB-API的参数替换。将?
作为占位符放置在要使用值的任何位置,然后提供一个值元组作为游标的execute()
方法的第二个参数。(其他数据库模块可能使用不同的占位符,例如%s或:1。)
在这种情况下,params是什么?@user1585507:字符串格式中
blablabla
部分的序列。要插入的值的顺序与?
占位符的顺序相同。我编辑了我的问题。我不明白为什么我写的东西不管用,它基本上和你的一样。不,我正忙着,没有得到任何反馈。我不知道如何获得错误,但我非常确定这样编写的请求正在崩溃。它使用的是我的蹩脚语法(除非字符串包含“@user1585507:”),你的蹩脚语法对SQL注入攻击非常开放。使用日志记录器和日志异常。“我在线程中执行此操作,因此无法轻松获得调试信息”。好吧,在线程中执行此操作之前,不要在线程中进行调试。