LoginSignup
4
4

More than 5 years have passed since last update.

pythonでsqliteにprotocol buffersを突っ込む

Posted at

3行で

sqliteにprotocol buffersのシリアライズされたデータを突っ込みます。

  1. sqliteにblobのカラムを作る
  2. 突っ込むときはbuffer
  3. 読み込むときはstr

(protobuf関係なくてただバイナリとして扱ってるだけですね)

person.proto
message Person {
   optional string name = 1;
   optional int32 age = 2;
 }
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3
from person_pb2 import Person


if __name__ == '__main__':
    # データベースへの接続とデーブルの作成
    conn = sqlite3.connect(":memory:")
    c = conn.cursor()
    c.execute("create table people (person blob)")

    p = Person(name="John Doe", age=128)
    print p

    # 書き込み
    wb = buffer(p.SerializeToString())
    c.execute("insert into people values (?)", [wb])

    # 読み込み
    c.execute("select * from people")
    rb = c.fetchone()[0]
    q = Person()
    q.ParseFromString(str(rb))
    print q

結果

name: "John Doe"                                      
age: 128                                              

name: "John Doe"                                      
age: 128

読み書きできました。

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4