Created
August 25, 2023 16:28
-
-
Save ComputerTech312/a98184b16fc6a3161df33f0c8c128b44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
import os | |
def connect_to_sqlite(db_name): | |
"""Connects to an SQLite database or creates it if it doesn't exist.""" | |
connection = sqlite3.connect(db_name) | |
return connection | |
def create_table(connection, table_name): | |
cursor = connection.cursor() | |
try: | |
cursor.execute(f"CREATE TABLE {table_name} (id INTEGER PRIMARY KEY, data TEXT)") | |
print(f"Table {table_name} created successfully.") | |
except sqlite3.Error as err: | |
print(f"Error: {err}") | |
cursor.close() | |
def delete_table(connection, table_name): | |
cursor = connection.cursor() | |
try: | |
cursor.execute(f"DROP TABLE {table_name}") | |
print(f"Table {table_name} deleted successfully.") | |
except sqlite3.Error as err: | |
print(f"Error: {err}") | |
cursor.close() | |
def list_tables(connection): | |
cursor = connection.cursor() | |
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") | |
tables = cursor.fetchall() | |
cursor.close() | |
return [table[0] for table in tables] | |
def main(): | |
db_name = input("Enter SQLite database name (with .db extension): ") | |
if not db_name.endswith(".db"): | |
db_name += ".db" | |
connection = connect_to_sqlite(db_name) | |
while True: | |
print("\nOptions:") | |
print("1. Create a new table") | |
print("2. Delete an existing table") | |
print("3. List all tables") | |
print("4. Exit") | |
choice = input("Enter your choice: ") | |
if choice == '1': | |
table_name = input("Enter table name to create: ") | |
create_table(connection, table_name) | |
elif choice == '2': | |
table_name = input("Enter table name to delete: ") | |
delete_table(connection, table_name) | |
elif choice == '3': | |
print("Tables:") | |
for table in list_tables(connection): | |
print(table) | |
elif choice == '4': | |
connection.close() | |
break | |
else: | |
print("Invalid choice. Please try again.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment