您的位置:首页 > 编程语言 > Python开发

[Python]sqlite3二进制文件存储问题(BLOB)(You must not use 8-bit bytestrings unless you use a text_factory...)

2014-08-09 23:36 656 查看
事情是这样的:

博主尝试用Python的sqlite3数据库存放加密后的用户名密码信息,表是这样的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()



微博:@浙大宋博
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐