<Pandas, peewee, sqlite> peeweeを少しためす。

peeweeを少しためしてみた。

まずは、データベースdatabase作成とデータ登録。

In [51]: from peewee import *

In [52]: db = SqliteDatabase('people.db')

In [53]: class Person(Model):
    ...:     name = CharField()
    ...:     birthday = DateField()
    ...:     is_relative = BooleanField()
    ...:     class Meta:
    ...:         database = db
    ...:         

In [54]: db.connect()

In [55]: db.create_tables([Person])

In [57]: from datetime import date

In [58]: hage = Person(name='Hage', birthday=date(1960,1,1), is_relative=True)

In [59]: hage.save()
Out[59]: 1

In [60]: hige = Person(name='Hige', birthday=date(1960,1,2), is_relative=True)

In [61]: hige.save()
Out[61]: 1

で、次に登録したデータの読出し。

In [62]: Person.select()
Out[62]: <class '__main__.Person'> SELECT "t1"."id", "t1"."name", "t1"."birthday", "t1"."is_relative" FROM "person" AS t1 []

In [63]: for p in Person.select():
    ...:     print(p.name, p.birthday, p.is_relative)
    ...:     
Hage 1960-01-01 True
Hige 1960-01-02 True

データベースの場合、pandasさんで読みだすと楽なので、ためす。

In [64]: import pandas as pd

In [65]: pd.io.sql.read_sql('SELECT * FROM Person', db)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-65-bdc8325f4385> in <module>()
----> 1 pd.io.sql.read_sql('SELECT * FROM Person', db)

C:\Anaconda3\Lib\site-packages\pandas\io\sql.py in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    497             sql, index_col=index_col, params=params,
    498             coerce_float=coerce_float, parse_dates=parse_dates,
--> 499             chunksize=chunksize)
    500 
    501     try:

C:\Anaconda3\Lib\site-packages\pandas\io\sql.py in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
   1593 
   1594         args = _convert_params(sql, params)
-> 1595         cursor = self.execute(*args)
   1596         columns = [col_desc[0] for col_desc in cursor.description]
   1597 

C:\Anaconda3\Lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs)
   1553             cur = self.con
   1554         else:
-> 1555             cur = self.con.cursor()
   1556         try:
   1557             if kwargs:

AttributeError: 'SqliteDatabase' object has no attribute 'cursor'

エラー。
どうもpeeweeのコネクションでは動かないらしい。
しょうがないので、sqlite3モジュールをコール。

In [66]: import sqlite3

In [67]: con = sqlite3.connect('people.db')

In [68]: pd.io.sql.read_sql('SELECT * FROM Person', con)
Out[68]: 
   id  name    birthday  is_relative
0   1  Hage  1960-01-01            1
1   2  Hige  1960-01-02            1

こちらにお世話になった。

qiita.com

あとマニュアル。

peewee — peewee 2.8.5 documentation