Advertisement
DrAungWinHtut

dboop.py

Jul 16th, 2023
1,114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.71 KB | None | 0 0
  1. import sqlite3
  2.  
  3. class Database:
  4.     def __init__(self, db_name):
  5.         try:
  6.             self.conn = sqlite3.connect(db_name)
  7.             self.cursor = self.conn.cursor()
  8.             print(f"Connected to the database: {db_name}")
  9.         except sqlite3.Error as e:
  10.             print(f"Error connecting to the database: {e}")
  11.  
  12.     def create_table(self, table_name, columns):
  13.         try:
  14.             query = f"CREATE TABLE IF NOT EXISTS {table_name} ({columns})"
  15.             self.cursor.execute(query)
  16.             self.conn.commit()
  17.             print(f"Table '{table_name}' created successfully.")
  18.         except sqlite3.Error as e:
  19.             print(f"Error creating table: {e}")
  20.  
  21.     def insert_data(self, table_name, data):
  22.         try:
  23.             columns = ", ".join(data.keys()) # id, name, age
  24.             print(f'kyes are {data.keys()}')
  25.             print(f'values are {data.values()}')
  26.             print(f'columns are {columns}')
  27.             values = ", ".join([f"'{value}'" for value in data.values()])
  28.             print(f'values become {values}')
  29.             query = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"
  30.             print(query)
  31.             self.cursor.execute(query)
  32.             self.conn.commit()
  33.             print("Data inserted successfully.")
  34.         except sqlite3.Error as e:
  35.             print(f"Error inserting data: {e}")
  36.  
  37.     def fetch_data(self, table_name, condition=None):
  38.         try:
  39.             query = f"SELECT * FROM {table_name}"
  40.             if condition:
  41.                 query += f" WHERE {condition}"
  42.             self.cursor.execute(query)
  43.             data = self.cursor.fetchall()
  44.             return data
  45.         except sqlite3.Error as e:
  46.             print(f"Error fetching data: {e}")
  47.  
  48.     def update_data(self, table_name, data, condition=None):
  49.         try:
  50.             set_values = ", ".join([f"{key}='{value}'" for key, value in data.items()])
  51.             query = f"UPDATE {table_name} SET {set_values}"
  52.             if condition:
  53.                 query += f" WHERE {condition}"
  54.             self.cursor.execute(query)
  55.             self.conn.commit()
  56.             print("Data updated successfully.")
  57.         except sqlite3.Error as e:
  58.             print(f"Error updating data: {e}")
  59.  
  60.     def delete_data(self, table_name, condition=None):
  61.         try:
  62.             query = f"DELETE FROM {table_name}"
  63.             if condition:
  64.                 query += f" WHERE {condition}"
  65.             self.cursor.execute(query)
  66.             self.conn.commit()
  67.             print("Data deleted successfully.")
  68.         except sqlite3.Error as e:
  69.             print(f"Error deleting data: {e}")
  70.  
  71.     def close_connection(self):
  72.         try:
  73.             self.cursor.close()
  74.             self.conn.close()
  75.             print("Connection closed.")
  76.         except sqlite3.Error as e:
  77.             print(f"Error closing connection: {e}")
  78.  
  79.  
  80. # Example usage:
  81. db = Database("mydatabase.db")
  82.  
  83. # Create a table
  84. db.create_table("employees", "id INTEGER PRIMARY KEY, name TEXT, age INTEGER")
  85.  
  86. # Insert data into the table
  87. data = {
  88.     "id": 1,
  89.     "name": "John Doe",
  90.     "age": 30
  91. }
  92. data1 = {
  93.     "id": 2,
  94.     "name": "Green Hackers",
  95.     "age": 40
  96. }
  97. db.insert_data("employees", data)
  98. db.insert_data("employees", data1)
  99.  
  100. # Fetch all data from the table
  101. all_data = db.fetch_data("employees")
  102. print(all_data)
  103.  
  104. # Update data in the table
  105. new_data = {
  106.     "name": "Jane Smith",
  107.     "age": 32
  108. }
  109. db.update_data("employees", new_data, "id = 1")
  110.  
  111. # Fetch updated data
  112. updated_data = db.fetch_data("employees", "id = 1")
  113. print(updated_data)
  114.  
  115. # Delete data from the table
  116. # db.delete_data("employees", "id = 1")
  117.  
  118. # Close the database connection
  119. db.close_connection()
  120.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement