python增删查改一段完整的代码
时间: 2024-03-02 21:28:13 浏览: 17
这里是一个简单的 Python 代码,实现了增删查改操作:
```
# 初始化一个字典作为数据存储
data = {}
# 添加数据
def add_data(key, value):
data[key] = value
# 删除数据
def delete_data(key):
if key in data:
del data[key]
else:
print("Error: Key not found in data.")
# 查询数据
def query_data(key):
if key in data:
return data[key]
else:
print("Error: Key not found in data.")
# 修改数据
def update_data(key, value):
if key in data:
data[key] = value
else:
print("Error: Key not found in data.")
```
使用方式:
```
# 添加数据
add_data("name", "Tom")
add_data("age", 25)
# 查询数据
print(query_data("name")) # 输出 "Tom"
# 修改数据
update_data("age", 26)
# 删除数据
delete_data("name")
```
相关问题
python的pymysql的增删查改代码
好的,以下是Python中使用pymysql进行增删查改的代码示例:
1. 连接数据库
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="password", database="test")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
```
2. 插入数据
```python
# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('John', 'Doe', 20, 'M', 2000)"
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
```
3. 查询数据
```python
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income))
except:
print("Error: unable to fetch data")
```
4. 更新数据
```python
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
```
5. 删除数据
```python
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 发生错误时回滚
db.rollback()
```
6. 关闭数据库连接
```python
# 关闭数据库连接
db.close()
```
python与mysql增删查改代码操作
好的,以下是Python操作MySQL数据库的增删查改代码示例:
连接 MySQL 数据库:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306, charset='utf8mb4')
# 获取游标
cursor = db.cursor()
```
增加数据:
```python
# 插入数据
sql = "INSERT INTO `student` (`id`, `name`, `age`, `gender`) VALUES (%s, %s, %s, %s)"
param = (1, 'Tom', 18, 'male')
cursor.execute(sql, param) # 执行 SQL 语句
db.commit() # 提交修改
```
删除数据:
```python
# 删除数据
sql = "DELETE FROM `student` WHERE `id`=%s"
param = (1,)
cursor.execute(sql, param)
db.commit()
```
查询数据:
```python
# 查询数据
sql = "SELECT * FROM `student`"
cursor.execute(sql)
result = cursor.fetchall() # 获取所有数据
for row in result:
print(row)
```
修改数据:
```python
# 修改数据
sql = "UPDATE `student` SET `age`=%s WHERE `id`=%s"
param = (20, 1)
cursor.execute(sql, param)
db.commit()
```
注意:以上代码仅供参考,实际在使用时需要根据具体的情况进行修改。同时,操作数据库需要谨慎,防止造成数据损失。