开发者

With python sqlite3 module, how to deal with fields that contain double-quotes?

I was trying to access a database that has data that contains "" such as:

Tom "is" a cat.

When I use this code:

m开发者_StackOverflow中文版yData = 100; myKey = 'Tom "is" a cat.'

myCursor.execute('UPDATE MyTable SET MyField = %d WHERE MyTable.Key == "%s"' % (myData, myKey))

I got this error

sqlite3.OperationalError: near "is": syntax error

Note that I've enclosed my %s with "". I've also tried to use single-quotes around it or adding \, neither worked. Any idea how to solve this?


Use DB-API parameter substitution and leave the formatting to sqlite3 library:

myCursor.execute('UPDATE MyTable SET MyField = ? WHERE MyTable.Key == ?', (myData, myKey))


You should not use double quote for surrounding strings in sql statement, thus you should use single quote in the statement:

myData = 100 
myKey = 'Tom "is" a cat.'
myCursor.execute('''UPDATE MyTable SET MyField = %d WHERE MyTable.Key ='%s' ''' % (myData, myKey))

Triple single quote allows you to use single quotes as if you are in a text editor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜