我正在尝试将从文件中读取的字符串插入到 Python 中的 sqlite
数据库中。这些字符串有空格(换行符、制表符和空格),也有单引号或双引号的外观。这是我尝试这样做的方法:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE test
(a text, b text)''')
f = open("foo", "w")
f.write("hello\n\'world\'\n")
f.close()
testfield = open("foo").read()
# Insert a row of data
c.execute("INSERT INTO test VALUES ('%s', 'bar')" %(testfield))
# Save (commit) the changes
conn.commit()
我发现这失败了,错误是:
c.execute("INSERT INTO test VALUES ('%s', 'bar')" %(testfield))
sqlite3.OperationalError: near "world": syntax error
我怎样才能做到这一点?在插入数据库之前是否需要对字符串进行转义,如果需要如何转义?谢谢。
最佳答案
您使用 SQL 参数而不是字符串格式:
c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))
当使用 SQL 参数时,您让数据库库处理引用,甚至更好的是,让数据库优化查询并将优化的查询计划重新用于同一基本查询(使用不同参数)的多次执行。
最后但同样重要的是,您可以更好地抵御 SQL 注入(inject)攻击,因为数据库最了解如何转义危险的类似 SQL 的值。
Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see http://xkcd.com/327/ for humorous example of what can go wrong).
Instead, use the DB-API’s parameter substitution. Put
?
as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’sexecute()
method.
关于python - 如何使用 Python 将带有引号和换行符的字符串插入到 sqlite 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695134/