python的pymysql的增删查改代码
时间: 2024-02-18 08:56:47 浏览: 108
好的,以下是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()
```
阅读全文