2017-04-26 84 views
0

我建有这样的元组的字符串:解码字符串:Python的

t = tuple(data) 
querysring="INSERT INTO %s VALUES %s "%(table,t) 

当我打印字符串的结果是:

INSERT INTO AGENT VALUES ('Bock', 'Fran\\xc3\\xa7ois Bock', 'Individual', 'fb****@mail.com') 

但我想是这样的:

INSERT INTO AGENT VALUES ('Bock', 'François Bock', 'Individual', 'fb****@mail.com') 

可以解码字符串吗? 我使用Python2.x,但我可以用Python3.x

我试试这个:

querysring=u"INSERT INTO %s VALUES %s "%(table,t) 
print(ftfy.fix_text(querysring)) 

但它不工作

+0

我不知道这个问题是如何从您刚才的问题http://stackoverflow.com/questions/显著不同43629059 /编码在元组-蟒。此外,你不应该使用Python字符串格式来生成你的查询,你应该有参数化的查询,它本身可以解决你的问题。 – roganjosh

+0

是的,但我该怎么做?我不知道数组中的数字值(数据) –

+0

python2将##编码:utf-8 - * - 编入第一行。 – Kadir

回答

1

我觉得你的问题是肤浅的,涉及到如何print显示器列出和列出不同的项目。列表的打印输出为ascii,即使内的列表在utf-8中正确编码。首先,使用chardet库:

from chardet.universaldetector import UniversalDetector 

a = ['Bock', 'François Bock'] 

detector = UniversalDetector() 
detector.feed(str(a)) 
detector.close() 

print "Encoding for the str(list): ", detector.result 

detector = UniversalDetector() 
detector.feed(a[1]) 
detector.close() 

print "Encoding for list[1]:  ", detector.result 

print "The whole list:    ", a 
print "Item in list:    ", a[1] 
从倒胃口打印

除此之外,它可能仍然写入数据库与参数化查询正确的编码。下面的代码的最后一部分写入文件,以确认数据编码被保留:

import sqlite3 

conn = sqlite3.connect(":memory:") 
conn.text_factory = str 
c = conn.cursor() 

c.execute("CREATE TABLE IF NOT EXISTS testing(test1 TEXT, test2 TEXT)") 
conn.commit() 

my_tuple = 'Bock', 'François Bock' 
table = 'testing' 

placeholders = ', '.join('?' for item in my_tuple) 
query = "INSERT INTO {} VALUES ({})".format(table, placeholders) 

c.execute(query, my_tuple) 

c.execute("SELECT * FROM testing") 
all_data = c.fetchone() 

# Check the printouts 
print all_data 
print all_data[1] 

# For good measure, write them to a file 
with open('check_output.txt', 'w') as outfile: 
    outfile.write(', '.join(item for item in all_data)) 
+0

谢谢你的帮助和你的解释。我使用psycopg2,所以参数化查询有点不同,但它真的帮助我! –

+0

@FrancoisBock不用客气,是'%s'而不是'''?无论采用哪种方式,都不要使用字符串格式,这会让您打开SQL注入。 – roganjosh

+0

是的,就是这个“'%s'” –