我正在尝试将从文件中读取的字符串插入到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
我该如何实现这个?在插入数据库之前,这些字符串需要进行转义吗?如果需要,应该怎么做?谢谢。
CREATE TABLE 'test' (a text, b text)
,这不是有效的SQL语句。这是一件好事。 - Martijn Pieters