zoukankan      html  css  js  c++  java
  • python用法:处理sqlite中的中文字符时遇到的问题

    python用法:处理sqlite中的中文字符时遇到的问题 - iihero@CSDN - 博客频道 - CSDN.NET


    python用法:处理sqlite中的中文字符时遇到的问题


    1472人阅读
    评论(0)
    收藏
    举报

    作为初学才,学起python,是挺快,但是也不免常常出些小错。在访问sqlite3的时候,我写了下边的测试代码。

    文件test.py是utf-8编码的,OK,结果没问题。

    #!/usr/bin/env python
    #
    coding=utf-8

    import sqlite3

    #con=sqlite3.connect(r"sqlite.db")
    con=sqlite3.connect(r"e: estsqlite3.db")
    #con.text_factory=str
    cur = con.cursor()
    #cur.execute("insert into basvslvoy (vslcode,voyage,vslename) values(?,?,?)",(u'tt', u'tt', u'tt'))
    cur.execute("insert into t1 values(?, ?)", (10, u'中文测试gbk10' ))
    con.commit()
    cur.execute(u
    "select * from t1 where col2 like '中%'")
    for row in cur.fetchall():
        
    print row[0], row[1].encode('gbk')

    con.close()

    结果如下:

    Process started >>>
    10 中文测试gbk10
    10 中文测试gbk10
    5 中
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10
    10 中文测试gbk10<<< Process finished.

    可是,当我把文件编码调整成ansi格式的时候,上边程序没办法跑。
    结果将文件内容改成下边的样子:

    #!/usr/bin/env python
    #
    coding=utf-8

    import sqlite3

    #con=sqlite3.connect(r"sqlite.db")
    con=sqlite3.connect(r"e: estsqlite3.db")
    #con.text_factory=str
    cur = con.cursor()
    #cur.execute("insert into basvslvoy (vslcode,voyage,vslename) values(?,?,?)",(u'tt', u'tt', u'tt'))
    cur.execute("insert into t1 values(?, ?)", (10'中文测试gbk10'.decode('gbk') ))
    con.commit()
    cur.execute(
    "select * from t1 where col2 like '" + ''.decode('gbk')+"%'")
    for row in cur.fetchall():
        
    print row[0], row[1].encode('gbk')


    con.close()

    这样,出现的结果跟上边一样。
    问题的关键就是#coding=utf-8,同时文件编码也要是utf-8,才能让结果保持一致。
    看看下边的简单例子就知道:

    >>> a = '中文'
    >>> b = u'中文'
    >>> a
    'ÖÐÎÄ'
    >>> b
    u
    '中文'
    >>> a.decode('gbk')
    u
    '中文'
    >>> b == a.decode('gbk')
    True

    如果将上边的例子放到一个.py文件当中,分别采用utf-8编码和ansi编码('cp936'),结果可能就是分别为True和False。

  • 相关阅读:
    Plotagraph软件五分钟光速速成傻瓜教程
    QT插件+ROS 2 新建项目
    QT插件+ROS 1 安装配置
    GitHub 优秀的 Android 开源项目 (精品)
    ROS的launch文件
    编写第一个 Shell 脚本
    CMake 入门实战
    ROS 创建服务和请求
    ROS 小乌龟测试
    【转】C++中的虚函数的实现
  • 原文地址:https://www.cnblogs.com/lexus/p/2400053.html
Copyright © 2011-2022 走看看