[PYTHON] A class that creates DB creation-data insertion with SQLite3 quickly

Purpose

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.

What is this class?

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.

Click here for source code

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

A class that creates DB creation-data insertion with SQLite3 quickly
[Python] A program that creates stairs with #
[Python / Tkinter] A class that creates a scrollable Frame
Develop a web API that returns data stored in DB with Django and SQLite
[python] I made a class that can write a file tree quickly
[Python] Inherit a class with class variables
Created Simple SQLite, a Python library that simplifies SQLite table creation / data insertion
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
A class that hits the DMM API
Save / load in-memory DB with python sqlite3
A typed world that begins with Python
PGM that automatically creates a walking route