How to create a table in a database with sqlite3 and Python

In the following video we will get how to create databases with sqlite3 and python. The code that will result will be the following

import sqlite3 as lite


conn = lite.connect("db01.db")
print(conn)

# Create a table

tablename = "profile"

def create_table():
	cur = conn.cursor()
	command = "CREATE TABLE IF NOT EXISTS"
	fields = "id INTEGER PRIMARY KEY, name TEXT, surname TEXT"
	cur.execute(f"{command} {tablename}({fields})")
	conn.commit()

def insert_data():
	data = (
		("John", "Smith"),
		("Jane", "Austin")
		)

	cur = conn.cursor()
	command = "INSERT INTO"
	fields = "id, name, surname"

	for n, d in enumerate(data):
		name, surname = d
		cur.execute(f"{command} {tablename}({fields}) VALUES ({n}, '{name}', '{surname}')")
		conn.commit()

def show_data():
	cur = conn.cursor()
	cur.execute("SELECT * FROM " + tablename)
	rows = cur.fetchall()
	for r in rows:
		print(r)

show_data()

conn.close()

So we can:

  • create a database
  • create a table
  • insert data
  • see data

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.