如何在sqlite3中插入中文字符

 我来答
xiangjuan314
2016-04-18 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2879万
展开全部
第一种,设置text_factory = str

#-*-encoding:utf-8-*-

import sqlite3

def create_tables(dbname):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
cursor.execute('''create table userinfo(name text, email text)''')
conn.commit()
cursor.close()
conn.close()

def drop_tables(dbname):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
cursor.execute('''drop table userinfo''')
conn.commit()
cursor.close()
conn.close()

def insert():
users = ('腾讯qq', 'qq@example.com')
conn = sqlite3.connect(dbname)
conn.text_factory = str ##!!!
cursor = conn.cursor()
cursor.execute("insert into userinfo(name, email) values(?, ?)", users)
conn.commit()
cursor.close()
conn.close()

def select(text):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
print "select name from userinfo where email='%s'" % text
for row in cursor.execute("select name from userinfo where email= ? ", (text,)):
print row[0]

if __name__ == '__main__':
dbname = 'test.db'
try:
drop_tables(dbname)
except:
pass
create_tables(dbname)
insert()
select("qq@example.com")
drop_tables(dbname)

第二种,把插入的数据转换为unicode:
#-*-encoding:utf-8-*-

import sqlite3

def create_tables(dbname):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
cursor.execute('''create table userinfo(name text, email text)''')
conn.commit()
cursor.close()
conn.close()

def drop_tables(dbname):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
cursor.execute('''drop table userinfo''')
conn.commit()
cursor.close()
conn.close()

def insert():
users = ('腾讯qq'.decode('utf8'), 'qq@example.com')
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
cursor.execute("insert into userinfo(name, email) values(?, ?)", users)
conn.commit()
cursor.close()
conn.close()

def select(text):
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
print "select name from userinfo where email='%s'" % text
for row in cursor.execute("select name from userinfo where email= ? ", (text,)):
print row[0].encode('utf8')

if __name__ == '__main__':
dbname = 'test.db'
try:
drop_tables(dbname)
except:
pass
create_tables(dbname)
insert()
select("qq@example.com")
drop_tables(dbname)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式