Python保存二进制数据到sqlite3

时间:2020-12-15 23:02:04

我们有这样一个需求:要保存二进制文件到数据库,以后还要从数据库读出来使用。到网上g了一下,发现可以实现,记录以备忘。

 

Python代码  Python保存二进制数据到sqlite3
  1. # coding: utf8  
  2.   
  3. # Python2.6.2  
  4.   
  5. import sqlite3  
  6.   
  7. db = sqlite3.connect('test.db')  
  8. cur = db.cursor()  
  9.   
  10. cur.execute("CREATE TABLE if not exists t (b BLOB);")  
  11.   
  12. with open('0.bin''rb') as f:  
  13.     cur.execute("insert into t values(?)", (sqlite3.Binary(f.read()), ))  
  14.     db.commit()  
  15.   
  16. cur.execute('select b from t limit 1')  
  17. b = cur.fetchone()[0]  
  18.   
  19. with open('00.bin''wb') as f:  
  20.     f.write(b)  
  21.   
  22. db.close()