2
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLite3のテーブル作成とPythonによるデータ操作

Posted at

この記事はSQLite3とPythonを使って簡易RDBを操作するものである。

環境

  • windows 10 Home
  • Python 3.6 系
  • SQLite3 3.27

DBテーブルの作成

db_table1.sqlite
create table xxx(
  id int primary key,
  name text,
)
db_table2.sqlite
create table yyy(
  id_y int,
  name2 text,
  foreign key(id_y) references xxx(id)
)

PythonのDB接続のクラスを作成

db_connet.py
class db_orm():
    def __init__(self, sqlite_db_path):
        self.db_path = sqlite_db_path
        self.conn = None
        self.cursor = None
        self.db_cursor()
    
    def db_connect(self):
        if self.conn is not None:
            self.db_close()
        self.conn = sqlite3.connect(self.db_path)
        
    def db_cursor(self):
        if self.conn is None:
            self.db_connect()
        if self.cursor is None:
            self.cursor = self.conn.cursor()
            
    def db_commit(self):
        self.conn.commit()
    
    def db_execute(self, exec_sql):
        # Insert a row of data
        # sample sql source
        # c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
        if self.cursor is None:
            self.db_cursor()
        return self.cursor.execute(exec_sql)
    
    def db_execute_many(self, exec_sql, data):
        if self.cursor is None:
            self.db_cursor()
        return self.conn.executemany(exec_sql, data)
        
    def db_close(self):
        if self.conn is not None:
            self.conn.close()
        self.cursor = None
        self.conn = None

dbに接続する

sqlite_path = '<dbのファイルパス>'
db_obj = db_orm(sqlite_path)

dbとの接続を終了する

db_obj.db_close()

sqlクエリを投げ、データを確認する

exe_sql = 'select * from xxx'
result = db_obj.db_execute(exe_sql).getchAll()

※ SELECT, DELETE, INESERTはどれも実行することができる

pandasでのデータ取得と登録

exe_sql = 'SELECT * FROM xxx'
df = pd.read_sql_query(exe_sql, db_obj.conn)

df.to_sql('xxx', db_obj.conn, index=False, if_exists='append', index_label='id')
2
7
0

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
2
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?