[英]Escaping backslash while inserting in sqlite using Python
I am a beginner in Python. 我是Python的初学者。 I am trying to insert the following data in sqlite db using Python 3.4.
我正在尝试使用Python 3.4在sqlite db中插入以下数据。
('config.xml', '09/12/2017 10:33:55 PM', 466, 'C:Users\\ron\\Downloads\\folder');
But I am getting an error 但是我遇到一个错误
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 23-26: truncated \\UXXXXXXXX escape
I think this is because of this character - \\
我认为这是因为这个角色-
\\
How can I tell sqlite to escape this character. 我怎样才能告诉sqlite逃脱这个角色。
Code -- 代码-
def create_filedetail(conn, filedetail):
"""
Create a new file detail into the filedetail table
:param conn:
:param filedetail:
:return: filedetail id
"""
sql = ''' INSERT INTO filedetail(filename,modified_date,filesize,filepath)
VALUES(?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, filedetail)
return cur.lastrowid
def main():
database = r"C:\Users\ron\Documents\sqlitedb\filedb.db"
sql_create_file_detail_table = """ CREATE TABLE IF NOT EXISTS filedetail (
id integer PRIMARY KEY,
filename text NOT NULL,
modified_date text,
filesize integer,
filepath text
); """
conn = create_connection(database)
if conn is not None:
# create filedetail table
create_table(conn, sql_create_file_detail_table)
with conn:
# create a new filedetail
filedetail = ('config.xml', '09/12/2017 10:33:55 PM', 466, "C:Users\ron\Downloads\folder");
filedetail_id = create_filedetail(conn, filedetail)
else:
print("Error! cannot create the database connection.")
Any help is highly appreciated. 非常感谢您的帮助。 Thanks in advance.
提前致谢。
You can see that there is a similar issue in this post: 您可以看到此帖子中存在类似的问题:
What exactly do "u" and "r" string flags do, and what are raw string literals? “ u”和“ r”字符串标志的作用是什么,什么是原始字符串文字?
Basically, you can create a string literal by prepending an r to your string. 基本上,您可以通过在字符串前面加上r来创建字符串文字 。
Look at this example. 看这个例子。 It returns an invalid character:
它返回一个无效字符:
>>> mypath = "C:Users\ron\Downloads\folder"
>>> mypath
'C:Users\ron\\Downloads\x0colder'
However, if you use the string literals: 但是,如果使用字符串文字:
>>> mypath = r"C:Users\ron\Downloads\folder"
>>> mypath
'C:Users\\ron\\Downloads\\folder'
You can then insert this new string into your SQL table. 然后,您可以将此新字符串插入SQL表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.