# -*- coding: utf-8 -*-
import sqlite3 conn = sqlite3.connect('SWC_Perf_Info.db')
cur = conn.cursor() test_sql1 = "INSERT INTO test (name) VALUES ('我爱中国')" #gbk编码,存入数据库的时候显示的是乱码
cur.execute(test_sql1)
conn.commit()
cursor = cur.execute("SELECT name from test")
for row in cursor:
print(row[0]) #因为读取的是GBK编码内容,所以可以直接显示
test_sql2 = "INSERT INTO test (name) VALUES ('我爱中国')".decode('GBK') #unicode编码
cur.execute(test_sql2)
conn.commit()
cursor = cur.execute("SELECT name from test")
for row in cursor:
print(row[0].decode('utf-8')) #即使用的是Unicode写入的数据库,内部还是使用的UTF-8编码存入,所以需要使用UTF-8解码
print(row[0].decode('utf-8').encode('GBK')) #输出的时候可以使用Unicode输出也可以使用本地的GBK输出
test_sql3 = test_sql2.encode('utf-8') #utf-8编码
cur.execute(test_sql3)
conn.commit()
cursor = cur.execute("SELECT name from test")
for row in cursor:
print(row[0].decode('utf-8'))
print(row[0].decode('utf-8').encode('GBK'))
select_sql1 = "SELECT name from test where name = '我爱中国'" #以GBK格式查询
cursor = cur.execute(select_sql1)
for row in cursor:
print(row[0].decode('utf-8'))
print(row[0].decode('utf-8').encode('GBK'))
#查询不到结果
6
select_sql2 = "SELECT name from test where name = '我爱中国'".decode('GBK') #以Unicode格式查询
cursor = cur.execute(select_sql2)
for row in cursor:
print(row[0].decode('utf-8'))
print(row[0].decode('utf-8').encode('GBK'))
select_sql3 = "SELECT name from test where name = '我爱中国'".decode('GBK').encode('utf-8') #以utf-8格式查询
cursor = cur.execute(select_sql3)
for row in cursor:
print(row[0].decode('utf-8'))
print(row[0].decode('utf-8').encode('GBK'))
总结下来写入的时候可以使用Unicode或者UTF-8编码的字符写入数据库
读取输出的时候使用UTF-8编码或者GBK编码的字符输出
查询的语句也必须是Unicode或者utf-8格式才能查询到结果
UTF-8是可以支持直接的读取或者输出理想编码格式