How to build a simple databse using Python

Creating a simple databse using Python Programming Language

  1. Import necessary modules: osshutil, and sqlite3.
1 import os
2 import shutil
3 import sqlite3
  1. It’s time to create a new folder to store the database:
1 os.makedirs('./mydatabase', exist_ok=True)
  1. Define a function to establish a connection to the database:

1 def create_connection():
2 conn = None
3 try:
4 conn = sqlite3.connect('./mydatabase/mydatabase.db')
5 print(sqlite3.version)
6 except Error as e:
7 print(e)
8
9 return conn
  1. Define a function to create a table:

1 def create_table(conn):
2 try:
3 sql_create_users_table = """ CREATE TABLE IF NOT EXISTS users (
4 id integer PRIMARY KEY,
5 name text NOT NULL,
6 email text NOT NULL
7 ); """
8
9 if conn is not None:
10 conn.execute(sql_create_users_table)
11 else:
12 print("Error! cannot create the database connection.")
13 except Error as e:
14 print(e)
  1. Let’s now work with the definition of a function to insert data into the table:

1 def insert_data(conn):
2 sql_insert_data = """ INSERT INTO users (name,email) VALUES
3 ('John','john@gmail.com'),
4 ('Sara','sara@gmail.com')
5 """
6 conn.execute(sql_insert_data)
7 conn.commit()
  1. It is time to define a function to query data from the table:

1 def query_data(conn):
2 cursor = conn.cursor()
3 cursor.execute("SELECT id, name, email from users")
4 rows = cursor.fetchall()
5
6 for row in rows:
7 print(row)
  1. At this moment,  let’s use these functions to create the database, insert data, and query data:

1 note to do this...# Establish a connection to the database
2 conn = create_connection()
3
4 # Create a table
5create_table(conn)
6
7 # Insert data into the table
8 insert_data(conn)
9
10 # Query data from the table
11 query_data(conn)
12
13 # Close the connection to the database
14 conn.close()
  1. After running this script, you should have a folder named “mydatabase” containing a file named “mydatabase.db”. The “mydatabase.db” file is your database, and it contains a table named “users” with three columns: id, name, and email. The table has two rows of data: John’s and Sara’s email addresses and names.

Remember to replace the paths, file names, and database details with your own details.

Related posts:

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading