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

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: ๐Ÿ•ฐ๏ธ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • Vs code

    What is VS Code? ๐Ÿ’ป Visual Studio Code (VS Code) is a free, lightweight, and powerful code editor developed by Microsoft. It supports multiple programming languages (Python, JavaScript, Java, etc.) with: VS Code is cross-platform (Windows, macOS, Linux) and widely used for web development, data science, and general programming. ๐ŸŒ๐Ÿ“Šโœ๏ธ How to Install VS Code…

Leave a Reply

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