|
| 1 | +import sqlite3 |
| 2 | + |
| 3 | +def create_table(connection): |
| 4 | + cursor = connection.cursor() |
| 5 | + cursor.execute('''CREATE TABLE IF NOT EXISTS employees ( |
| 6 | + id INTEGER PRIMARY KEY, |
| 7 | + name TEXT, |
| 8 | + position TEXT, |
| 9 | + salary REAL |
| 10 | + )''') |
| 11 | + connection.commit() |
| 12 | + |
| 13 | +def insert_data(connection, name, position, salary): |
| 14 | + cursor = connection.cursor() |
| 15 | + cursor.execute("INSERT INTO employees (name, position, salary) VALUES (?, ?, ?)", |
| 16 | + (name, position, salary)) |
| 17 | + connection.commit() |
| 18 | + |
| 19 | +def update_salary(connection, employee_id, new_salary): |
| 20 | + cursor = connection.cursor() |
| 21 | + cursor.execute("UPDATE employees SET salary = ? WHERE id = ?", (new_salary, employee_id)) |
| 22 | + connection.commit() |
| 23 | + |
| 24 | +def query_data(connection): |
| 25 | + cursor = connection.cursor() |
| 26 | + cursor.execute("SELECT * FROM employees") |
| 27 | + rows = cursor.fetchall() |
| 28 | + |
| 29 | + print("\nEmployee Data:") |
| 30 | + for row in rows: |
| 31 | + print(f"ID: {row[0]}, Name: {row[1]}, Position: {row[2]}, Salary: {row[3]}") |
| 32 | + |
| 33 | +if __name__ == "__main__": |
| 34 | + database_name = "employee_database.db" |
| 35 | + |
| 36 | + connection = sqlite3.connect(database_name) |
| 37 | + print(f"Connected to {database_name}") |
| 38 | + |
| 39 | + create_table(connection) |
| 40 | + |
| 41 | + insert_data(connection, "John Doe", "Software Engineer", 75000.0) |
| 42 | + insert_data(connection, "Jane Smith", "Data Analyst", 60000.0) |
| 43 | + |
| 44 | + print("\nAfter Insertions:") |
| 45 | + query_data(connection) |
| 46 | + |
| 47 | + update_salary(connection, 1, 80000.0) |
| 48 | + |
| 49 | + print("\nAfter Update:") |
| 50 | + query_data(connection) |
| 51 | + |
| 52 | + connection.close() |
| 53 | + print(f"Connection to {database_name} closed.") |
0 commit comments