Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

リストを列に見立てて、列を拡張(追加)。DBMSにテーブル定義して値も格納する。

リストを列に見立て、列を拡張(追加)していけるクラス。
最終的にはDBMSにテーブル定義して値も格納する。

ファイルの名前とか、クラスの名前とか、どう表現すればよいのかやや悩み。

プログラム list_manager_for_table.py
import sqlite3

class list2d_for_table():
    def __init__(self,table_name):
        self.table_name = table_name
        self.column_names_list = []
        self.column_values_list = []
        self.column_type_list = []

        self.rows=None
    
    def concat_column(self,value_list, column_name, column_type):
        if self.rows is None:
            self.rows = len(value_list)
        elif self.rows != len(value_list):
            raise

        self.column_names_list.append(column_name)
        self.column_values_list.append(value_list)

        if column_type == "INTEGER" or column_type == "REAL" or column_type == "TEXT":
            self.column_type_list.append(column_type)
        else:
            # 型は「INTEGER」「REAL」「TEXT」に限る。
            raise ValueError("型は「INTEGER」「REAL」「TEXT」に限る。")

    def build_sql_create_table(self):
        # CREATE TABLE test_table ( pi INTEGER, alphabet TEXT )
        # 「NULL」「INTEGER」「REAL」「TEXT」「BLOB」

        internal = []
        for i in range(len(self.column_type_list)):
            word="{0} {1}".format(self.column_names_list[i], self.column_type_list[i])
            internal.append(word)
        
        sql = "CREATE TABLE {0} ( {1} )".format(self.table_name, ", ".join(internal))
        
        return sql

    def to_dbms(self, db_cursor):
        for i in range(self.rows):  # 全ての行に対して、
            internal=[]
            for col_index in range(len(self.column_type_list)):  # 各列に対して
                if self.column_type_list[col_index] == "TEXT":
                    internal.append(f"'{self.column_values_list[col_index][i]}'")
                else:
                    if self.column_values_list[col_index][i] is None:
                        internal.append('NULL')
                    else:
                        internal.append(str(self.column_values_list[col_index][i]))
            
            sql=f"INSERT INTO { self.table_name } VALUES ({', '.join(internal)})"
            db_cursor.execute(sql)

if __name__ == "__main__":

    x = list2d_for_table("test_table")
    y = [3, 1, 4, 1, 5, 9,  None,'null']
    z = ['a', 'b', 'c', 'd', 'e', 'f', 'None','null']

    x.concat_column(y,"pi","INTEGER")
    x.concat_column(z,"alphabet","TEXT")
    print(x.build_sql_create_table())


    con = sqlite3.connect(":memory:")
    con.isolation_level = None
    cur = con.cursor()
    cur.execute('PRAGMA temp_store=MEMORY;')
    cur.execute('PRAGMA journal_mode=MEMORY;')

    cur.execute(x.build_sql_create_table())

    for row in cur.execute("select sql from sqlite_master where type='table'"):
        print(row)

    x.to_dbms(cur)

    for row in cur.execute("select * from test_table"):
        print(row)
結果
CREATE TABLE test_table ( pi INTEGER, alphabet TEXT )
('CREATE TABLE test_table ( pi INTEGER, alphabet TEXT )',)
(3, 'a')
(1, 'b')
(4, 'c')
(1, 'd')
(5, 'e')
(9, 'f')
(None, 'None')
(None, 'null')