SQLite Database Manipulation Functions

  • Share this:

Code introduction


This code block includes a series of database manipulation functions based on the sqlite3 library, including creating a random table, inserting data, fetching a random record, and deleting a table.


Technology Stack : sqlite3

Code Type : Database Manipulation

Code Difficulty : Intermediate


                
                    
import sqlite3
import random

def generate_random_table_name():
    letters = 'abcdefghijklmnopqrstuvwxyz'
    return ''.join(random.choice(letters) for i in range(5))

def create_random_table(db_connection):
    table_name = generate_random_table_name()
    cursor = db_connection.cursor()
    cursor.execute(f'CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
    db_connection.commit()

def insert_random_data(db_connection, table_name):
    cursor = db_connection.cursor()
    cursor.execute(f'INSERT INTO {table_name} (name, age) VALUES (?, ?)', (f'Name_{random.randint(1, 1000)}', random.randint(18, 65)))
    db_connection.commit()

def fetch_random_record(db_connection, table_name):
    cursor = db_connection.cursor()
    cursor.execute(f'SELECT * FROM {table_name} WHERE id = ?', (random.randint(1, 10),))
    return cursor.fetchone()

def delete_random_table(db_connection, table_name):
    cursor = db_connection.cursor()
    cursor.execute(f'DROP TABLE IF EXISTS {table_name}')
    db_connection.commit()

# JSON representation of the code                
              
Tags: