1.将通讯录的信息导入到了sqlite3中
2.使用select查询出的结果为类似[(01,u'u30a4u0379u8159',u'。。。')]结果
3.现在想用python写select * from tabname where username='张某';这样的语句查询,可是查询不到,数据库中存在此条目
4.请问需要将“张某”编码后再查询?编码成什么呢?
--coding:gb2312--
import xlrd
import os
import sys
import sqlite3
def get_address():
stdi,stdo,stde=sys.stdin,sys.stdout,sys.stderr
reload(sys)
sys.stdin,sys.stdout,sys.stderr=stdi,stdo,stde
sys.setdefaultencoding('gb2312')
xlrd.Book.encoding = "gb2312"
if not os.path.exists('f:\address_list1.xlsx'):
xlsx = xlrd.open_workbook(r'f:\address_list1.xlsx')
#print xlsx.sheet_names()
#print type(xlsx.sheet_names())
sheet = xlsx.sheet_by_name('Sheet1')
#print sheet.nrows,sheet.ncols
row_name_data = sheet.row_values(0)
alllist = []
for num in range(sheet.nrows):
row_data = sheet.row_values(num)
alllist.append(row_data)
#print '&&&&&&&&',alllist
if not os.path.exists('f:\address_list1.xlsx'):
conn = sqlite3.connect(r'f:\test.db')
cur = conn.cursor()
conn.execute('''
CREATE TABLE user_address(
user_id INTEGER DEFAULT 0 PRIMARY KEY ,
user_name VARCHAR(15) NOT NULL,
local_number VARCHAR(15) DEFAULT 0 ,
phone_number INTEGER(15)
)
''')
query = 'INSERT INTO user_address VALUES (?,?,?,?)'
count = 1
for element in range(len(alllist)):
conn.execute(query,(element+1,alllist[element][0],alllist[element][1],alllist[element][2]))
count = count + 1
conn.commit()
conn = sqlite3.connect(r'f:\test.db')
cur = conn.cursor()
cur.execute('SELECT * FROM user_address where user_name="张某"')
result = cur.fetchall()
print result
get_address()
输出结果为[]
1,连接数据库时使用
charset='utf8'
;2,sql语句使用unicode形式拼接,最后encode成utf-8;