Random SQLite3 Database Operations in Python

  • Share this:

Code introduction


These functions are used to interact with SQLite3 databases, including creating connections, executing random SQL queries, and closing connections. These functions can be used to learn how to use Python and the sqlite3 library for database operations.


Technology Stack : The code uses the sqlite3 package and library to interact with SQLite3 databases, including creating connections, executing random SQL queries, and closing connections.

Code Type : The type of code

Code Difficulty :


                
                    
import sqlite3
import random

def get_random_connection():
    """
    Establish a random SQLite3 connection to a temporary in-memory database.
    """
    return sqlite3.connect(':memory:')

def execute_random_query(connection):
    """
    Execute a random SQL query on the given connection.
    """
    cursor = connection.cursor()
    random_query = random.choice([
        "SELECT * FROM sqlite_master;",
        "SELECT COUNT(*) FROM sqlite_master;",
        "SELECT * FROM sqlite_master WHERE type='table';",
        "INSERT INTO sqlite_master (name, type, tbl_name, rootpage, sql) VALUES ('test_table', 'table', 'test_table', 1, 'CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);');",
        "UPDATE sqlite_master SET sql='CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);' WHERE name='test_table';",
        "DELETE FROM sqlite_master WHERE name='test_table';"
    ])
    cursor.execute(random_query)
    if random_query.strip().lower().startswith("select"):
        return cursor.fetchall()
    else:
        connection.commit()
        return None

def close_connection(connection):
    """
    Close the given SQLite3 connection.
    """
    connection.close()