zoukankan      html  css  js  c++  java
  • [Python]sqlite3二进制文件存储问题(BLOB)(You must not use 8-bit bytestrings unless you use a text_factory...)

    事情是这种:


    博主尝试用Python的sqlite3数据库存放加密后的usernamepassword信息,表是这种

    CREATE TABLE IF NOT EXISTS user
    			(
    			userID INTEGER PRIMARY KEY AUTOINCREMENT,
    			userStudentID BLOB NOT NULL UNIQUE ON CONFLICT IGNORE,
    			userPassword BLOB NOT NULL
    			);

    当中userStudentID and UserPassword 储存成了BLOB类型,作为二进制存储。

    但当博主把加密后的字节串插入数据库时。却报出例如以下错误:

    sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

    显然它把博主的字节串当成了未经编码的字符串。

    此时不能參考它的做法。把text_factory 置为 str,这种话博主的密文就会被编码存放(如utf-8),而假设有些字节无法按utf-8编码的话,就会引发异常或被忽略。


    网上搜了好多文章,均没有解决博主的问题。

    后来还是找到了Official Document



    https://docs.python.org/2/library/sqlite3.html#module-sqlite3

    原来Python中与sqlite3的BLOB相应的数据类型为buffer,博主惊出一身冷汗,忙看了下自己的插入部分的代码:

    def insertUsernameAndPasswordToDB(conn, cu, username, password):
    	username = encrypt(username)
    	password = encrypt(password)
    	cu.execute("INSERT INTO user(userStudentID, userPassword) VALUES (?,?)", (username, password) )
    	conn.commit()

    測试了下username和password的数据类型

    print isinstance(username, str)
    print isinstance(password, str)
    
    结果均为True。怪不得sqlite3尝试把他们按字符串的形式存储。这里又涉及一个知识,sqlite3用的是动态的数据类型系统。它会依照数据的值来尝试将数据转换成数据库内部的标准类型。这里它就尝试将我的字节串密文转换成字符串。

    參考资料:http://www.cnblogs.com/kfqcome/archive/2011/06/27/2137000.html


    将username和password转换成buffer类型,问题解决。

    def insertUsernameAndPasswordToDB(conn, cu, username, password):
    	username = encrypt(username)
    	password = encrypt(password)
    	cu.execute("INSERT INTO user(userStudentID, userPassword) VALUES (?

    ,?)", (buffer(username), buffer(password)) ) conn.commit()





    微博:@浙大宋博

  • 相关阅读:
    转:spring-session
    转:SpringBoot项目如何进行打包部署
    事务的隔离级别
    获取打卡记录接口返回数据情况说明
    批注@SuppressWarnings 的作用
    mybatis-generator eclipse插件 使用方法
    几种常见数据库的driverClassName和url
    ssm 配置多个数据源
    常用正则表达式
    tomcat 配置成服务
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5079622.html
Copyright © 2011-2022 走看看