When you want to create a DB as a test at work I made it because I wanted a class that I could make right away. It's troublesome to make it every time ... It takes time and effort. Mostly for myself.
DB name, table name, column name, data to be inserted It is a class that creates a DB and shows the data as soon as it is ready.
Create_DB.py
import sqlite3
class Create_DB(object):
def __init__(self,db_name,tb_name,col_names):
self.db_name = db_name
self.tb_name = tb_name
self.cl_name = ",".join(col_names)
#Create a table with DB.
def create_db(self):
conn = sqlite3.connect(self.db_name)
curs = conn.cursor()
sql = "CREATE TABLE IF NOT EXISTS "+ self.tb_name + " ("+ self.cl_name + ")"
curs.execute(sql)
#Put the data in the table.
def insert_data(self,insert_col_names,datas):
conn = sqlite3.connect(self.db_name)
curs = conn.cursor()
col_name = ",".join(insert_col_names)
sql = "INSERT INTO "+ self.tb_name + " VALUES("+ col_name + ")"
curs.executemany(sql,datas)
conn.commit()
conn.close()
#View data
def show_all_data(self):
conn = sqlite3.connect(self.db_name)
curs = conn.cursor()
sql = "SELECT * FROM " + self.tb_name
curs.execute(sql)
for row in curs.fetchall():
print(row)
conn.commit()
conn.close()
if __name__ == '__main__':
db_name = "sample.db"
tb_name = "sample_table"
col_names = ["sample text","sample2 text"]#In the list
insert_col_names = [":sample",":sample2"]#Add ":".
datas = [("AIUEO",1),("Kakikukeko",2)]
db_instance = Create_DB(db_name,tb_name,col_names)
db_instance.create_db()
db_instance.insert_data(insert_col_names,datas)
db_instance.show_all_data()
that's all.
Recommended Posts