Python Program with Data Querying 🔍

Python Program with Data Querying 🔍

This script connects, creates, inserts data, and then executes SELECT * queries on both tables.

Python

import sqlite3
import os

# --- Configuration ---
DB_FILE = 'company.db'

# --- Sample Data (for insertion) ---
dept_data = [
    (10, 'ACCOUNTING', 'NEW YORK'), (20, 'RESEARCH', 'DALLAS'),
    (30, 'SALES', 'CHICAGO'), (40, 'OPERATIONS', 'BOSTON'),
    (50, 'MARKETING', 'SAN FRANCISCO')
]
emp_data = [
    (7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800.00, None, 20),
    (7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600.00, 300.00, 30),
    (7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250.00, 500.00, 30),
    (7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975.00, None, 20),
    (7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250.00, 1400.00, 30),
    (7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850.00, None, 30),
    (7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450.00, None, 10),
    (7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000.00, None, 20),
    (7839, 'KING', 'PRESIDENT', None, '1981-11-17', 5000.00, None, 10),
    (7844, 'TURNER', 'SALESMAN', 7698, '1981-09-08', 1500.00, 0.00, 30),
    (7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100.00, None, 20),
    (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950.00, None, 30),
    (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000.00, None, 20),
    (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300.00, None, 10),
    (8001, 'JAYNE', 'SALESMAN', 7698, '1982-03-01', 1400.00, 200.00, 30),
    (8002, 'KELLY', 'ANALYST', 7902, '1982-03-05', 3200.00, None, 20),
    (8101, 'BROWN', 'ENGINEER', 7566, '1983-01-10', 4000.00, None, 40),
    (8102, 'DAVIS', 'TECHNICIAN', 7788, '1983-02-15', 3500.00, None, 40),
    (8201, 'GARCIA', 'MARKETER', 7839, '1984-06-20', 2000.00, None, 50),
    (8202, 'EVANS', 'SPECIALIST', 7782, '1984-07-01', 2100.00, None, 50)
]
# -----------------------------------------------------------

# Clean up previous file for a fresh start (Optional)
if os.path.exists(DB_FILE):
    os.remove(DB_FILE)

# Connect to the database and get a cursor
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
print(f"Successfully connected to the database: {DB_FILE}")

# --- Table Creation and Data Insertion ---
cursor.execute('CREATE TABLE dept (deptno INTEGER PRIMARY KEY, dname TEXT NOT NULL, loc TEXT);')
cursor.execute('CREATE TABLE emp (empno INTEGER PRIMARY KEY, ename TEXT NOT NULL, job TEXT, mgr INTEGER, hiredate TEXT, sal REAL, comm REAL, deptno INTEGER, FOREIGN KEY (deptno) REFERENCES dept (deptno));')
cursor.executemany("INSERT INTO dept VALUES (?, ?, ?)", dept_data)
cursor.executemany("INSERT INTO emp VALUES (?, ?, ?, ?, ?, ?, ?, ?)", emp_data)
conn.commit()
print("Tables created and data inserted successfully.")

# ==========================================================
#                      DATA QUERYING
# ==========================================================

print("\n" + "="*50)
print("             QUERYING DATA RESULTS")
print("="*50)

# 1. Query Data from the 'dept' table
print("\n--- Department (dept) Table Records ---")
cursor.execute("SELECT deptno, dname, loc FROM dept")
# The fetchall() method retrieves all rows of the query result.
dept_records = cursor.fetchall() 

# Print the column headers
print(f"{'DEPTNO':<6} | {'DNAME':<12} | {'LOCATION':<15}")
print("-" * 37)

# Print the department records
for row in dept_records:
    # Use f-strings for formatted output
    print(f"{row[0]:<6} | {row[1]:<12} | {row[2]:<15}")


# 2. Query Data from the 'emp' table
print("\n--- Employee (emp) Table Records (First 10 for brevity) ---")
cursor.execute("SELECT empno, ename, job, sal, deptno FROM emp")
# Fetch the first 10 records for display brevity
emp_records = cursor.fetchmany(10)

# Print the column headers
print(f"{'EMPNO':<6} | {'ENAME':<10} | {'JOB':<12} | {'SALARY':<8} | {'DEPTNO':<6}")
print("-" * 47)

# Print the employee records
for row in emp_records:
    print(f"{row[0]:<6} | {row[1]:<10} | {row[2]:<12} | {row[3]:<8.2f} | {row[4]:<6}")

# -----------------------------------------------------------

# Close the connection
conn.close()
print("\nDatabase connection closed.")

Key Querying Commands Explained

  • cursor.execute("SELECT ... FROM table"): Executes the SQL query. SELECT * retrieves all columns. In the example, I specified columns for cleaner output.
  • cursor.fetchall(): Retrieves all rows from the result set returned by the last execute() call.
  • cursor.fetchmany(10): Retrieves the next set of rows from the result set, allowing you to limit the output (I used it to show only the first 10 employee records).
  • for row in records:: Iterates through the list of tuples returned by fetchall() or fetchmany(), where each tuple is a row from the database.

Similar Posts

  •  List operators,List Traversals

    In Python, lists are ordered, mutable collections that support various operations. Here are the key list operators along with four basic examples: List Operators in Python 4 Basic Examples 1. Concatenation (+) Combines two lists into one. python list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3,…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Indexing and Slicing for Writing (Modifying) Lists in Python

    Indexing and Slicing for Writing (Modifying) Lists in Python Indexing and slicing aren’t just for reading lists – they’re powerful tools for modifying lists as well. Let’s explore how to use them to change list contents with detailed examples. 1. Modifying Single Elements (Indexing for Writing) You can directly assign new values to specific indices. Example 1:…

Leave a Reply

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