我们有这样一个需求:要保存二进制文件到数据库,以后还要从数据库读出来使用。到网上g了一下,发现可以实现,记录以备忘。
- # coding: utf8
- # Python2.6.2
- import sqlite3
- db = sqlite3.connect('test.db')
- cur = db.cursor()
- cur.execute("CREATE TABLE if not exists t (b BLOB);")
- with open('0.bin', 'rb') as f:
- cur.execute("insert into t values(?)", (sqlite3.Binary(f.read()), ))
- db.commit()
- cur.execute('select b from t limit 1')
- b = cur.fetchone()[0]
- with open('00.bin', 'wb') as f:
- f.write(b)
- db.close()