python - 如何使用 Python 将带有引号和换行符的字符串插入到 sqlite 数据库中?

标签 python mysql sql database sqlite

我正在尝试将从文件中读取的字符串插入到 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 的值。

引用sqlite3 documentation :

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’s execute() method.

关于python - 如何使用 Python 将带有引号和换行符的字符串插入到 sqlite 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695134/

相关文章:

sql - PLI 关键字的用途是什么?

python - Gio.SimpleAction 不发出改变状态信号

php - 让 Supervisord 定期重启子进程

python - 如何通过 mod-wsgi 使用 FCKEditor 的图像上传和浏览器?

c# - 从 mysql 保存和检索图像

python - 如何在Dask中写入Elastic db?

python - 属性错误 : 'ModuleSpec' object has no attribute 'load_data_wrapper'

MySql 查询连接 3 个空行的表

mysql - Laravel/PDO 没有转义反斜杠或引号?

java - JBoss 上的 "java.sql.SQLException: OALL8 is in an inconsistent state"