└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # database-driver 2 | import sqlite3 3 | 4 | class DatabaseDriver: 5 | def __init__(self, db_name="database.db"): 6 | self.db_name = db_name 7 | self.connection = None 8 | self.cursor = None 9 | self.connect() 10 | 11 | def connect(self): 12 | """Establish a connection to the database.""" 13 | self.connection = sqlite3.connect(self.db_name) 14 | self.cursor = self.connection.cursor() 15 | print("Connected to database") 16 | 17 | def create_table(self, table_name, columns): 18 | """Create a table with specified columns.""" 19 | columns_definition = ", ".join([f"{col} {dtype}" for col, dtype in columns.items()]) 20 | query = f"CREATE TABLE IF NOT EXISTS {table_name} ({columns_definition})" 21 | self.cursor.execute(query) 22 | self.connection.commit() 23 | print(f"Table '{table_name}' created or already exists.") 24 | 25 | def insert_data(self, table_name, data): 26 | """Insert data into the specified table.""" 27 | placeholders = ", ".join(["?" for _ in data]) 28 | query = f"INSERT INTO {table_name} VALUES ({placeholders})" 29 | self.cursor.execute(query, tuple(data)) 30 | self.connection.commit() 31 | print("Data inserted successfully.") 32 | 33 | def fetch_data(self, table_name): 34 | """Fetch all data from the specified table.""" 35 | query = f"SELECT * FROM {table_name}" 36 | self.cursor.execute(query) 37 | return self.cursor.fetchall() 38 | 39 | def close(self): 40 | """Close the database connection.""" 41 | if self.connection: 42 | self.connection.close() 43 | print("Database connection closed.") 44 | 45 | # Example usage 46 | def main(): 47 | db = DatabaseDriver() 48 | db.create_table("users", {"id": "INTEGER PRIMARY KEY", "name": "TEXT", "age": "INTEGER"}) 49 | db.insert_data("users", (1, "Alice", 25)) 50 | db.insert_data("users", (2, "Bob", 30)) 51 | users = db.fetch_data("users") 52 | print("Users:", users) 53 | db.close() 54 | 55 | if __name__ == "__main__": 56 | main() 57 | 67889 58 | --------------------------------------------------------------------------------