CRUD python demo
时间: 2023-02-09 11:20:01 浏览: 103
:
Sure, I can help you with a CRUD (Create, Read, Update, Delete) demo in Python!
Here's a simple example to demonstrate CRUD operations on a database using SQLite in Python:
```python
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
# Create a table
conn.execute('''CREATE TABLE users (id INT PRIMARY KEY NOT NULL, name TEXT NOT NULL, age INT NOT NULL)''')
# Insert data into the table
conn.execute("INSERT INTO users (id, name, age) VALUES (1, 'John Doe', 25)")
conn.execute("INSERT INTO users (id, name, age) VALUES (2, 'Jane Doe', 30)")
# Read data from the table
cursor = conn.execute("SELECT id, name, age from users")
for row in cursor:
print("ID = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
# Update data in the table
conn.execute("UPDATE users SET age = 26 WHERE id = 1")
# Read data from the table again to see the update
cursor = conn.execute("SELECT id, name, age from users")
for row in cursor:
print("ID = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
# Delete data from the table
conn.execute("DELETE from users where id=2;")
# Read data from the table again to see the delete
cursor = conn.execute("SELECT id, name, age from users")
for row in cursor:
print("ID = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
# Commit the changes and close the connection
conn.commit()
conn.close()
```
Let me know if you need anything else!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)