在SQLite-Python中实现返回、查询中文字段的方法

yipeiwu_com6年前Python基础

博主在这个问题上卡了挺久的,贴出来解决方法帮助需要的朋友,直接上代码(测试环境:win10+Python2.7):

# coding=utf-8
 
import sqlite3
 
with sqlite3.connect(":memory:") as conn:
  try:
    init_sql = " create table test (id integer primary key ,name text(200) not null);" \
          " insert into test (name) values ('小居居');" \
          " insert into test (name) values ('大居居');"
    conn.executescript(init_sql)
  except Exception as e:
    conn.rollback()
    raise e
  else:
    conn.commit()
    conn.text_factory = str # 此处是关键,sqlite默认文本存取是Unicode
    try:
      for row in conn.execute(" select * from test where name = ?",("大居居",)):
        print row[1],type(row[1])
    except Exception as e:
      raise e

结果:

大居居 <type 'str'>

以上这篇在SQLite-Python中实现返回、查询中文字段的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现读取并保存文件的类

本文实例讲述了Python实现读取并保存文件的类。分享给大家供大家参考,具体如下: 这个类写在一个叫class_format.py 的文件里, 放在D盘 >>> i...

用Python+OpenCV对比图像质量的几种方法

用Python+OpenCV对比图像质量的几种方法

前言 图片的本质就是大量像素在二维平面上的组合,每个像素点用数字化方式记录颜色。可以直观的想象,一张图片就是一个巨大的电子栅格,每个格子内有一盏灯泡,这个灯泡可以变换256的三次方种颜色...

Python translator使用实例

1.string.maketrans设置字符串转换规则表(translation table) allchars = string.maketrans('...

python读取一个目录下所有txt里面的内容方法

实例如下所示: import os allFileNum = 0 def printPath(level, path): global allFileNum ''''' 打印一...

巧用Python装饰器 免去调用父类构造函数的麻烦

先看一段代码: 复制代码 代码如下: class T1(threading.Thread): def __init__(self, a, b, c): super(T1, self)._...