-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworking_with_databases(sqlite3).py
62 lines (49 loc) · 1.89 KB
/
working_with_databases(sqlite3).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import sqlite3
# 1. Connecting to a database
with sqlite3.connect("example.db") as connection:
cursor = connection.cursor()
# 2. Creating a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL
)
''')
connection.commit()
# 3. Inserting data into the table
user_data = [
('Alice', '[email protected]'),
('Bob', '[email protected]'),
('Charlie', '[email protected]')
]
cursor.executemany('INSERT INTO users (username, email) VALUES (?, ?)', user_data)
connection.commit()
# 4. Querying data from the table
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
print("All Users:")
for row in rows:
print(row)
# 5. Updating data in the table
cursor.execute('UPDATE users SET email = ? WHERE username = ?', ('[email protected]', 'Alice'))
connection.commit()
# 6. Deleting data from the table
cursor.execute('DELETE FROM users WHERE username = ?', ('Charlie',))
connection.commit()
# 7. Using context manager for transactions
cursor.execute('INSERT INTO users (username, email) VALUES (?, ?)', ('David', '[email protected]'))
# 8. Using named placeholders
new_user = ('Eve', '[email protected]')
cursor.execute('INSERT INTO users (username, email) VALUES (:username, :email)',
{'username': new_user[0], 'email': new_user[1]})
connection.commit()
# 9. Handling errors
try:
cursor.execute('INSERT INTO users (username) VALUES (?)', ('ErrorUser',))
connection.commit()
except sqlite3.Error as e:
print(f"Error: {e}")
# 10. Closing the connection
connection.close()
# Note: For more complex databases or other database systems, you might need to use additional libraries or connect to a database server.