pymysql 使用相关案例及异常处理
时间: 2023-10-24 21:25:54 浏览: 118
案例:
连接数据库:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = db.cursor()
# 执行SQL语句
sql = 'SELECT * FROM student'
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
# 关闭游标和数据库连接
cursor.close()
db.close()
print(result)
```
插入数据:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = db.cursor()
# 执行SQL语句
sql = "INSERT INTO student(name, age, sex) VALUES ('小明', 18, '男')"
try:
cursor.execute(sql)
db.commit()
print("插入数据成功")
except:
db.rollback()
print("插入数据失败")
# 关闭游标和数据库连接
cursor.close()
db.close()
```
更新数据:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = db.cursor()
# 执行SQL语句
sql = "UPDATE student SET age = 20 WHERE name = '小明'"
try:
cursor.execute(sql)
db.commit()
print("更新数据成功")
except:
db.rollback()
print("更新数据失败")
# 关闭游标和数据库连接
cursor.close()
db.close()
```
删除数据:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = db.cursor()
# 执行SQL语句
sql = "DELETE FROM student WHERE name = '小明'"
try:
cursor.execute(sql)
db.commit()
print("删除数据成功")
except:
db.rollback()
print("删除数据失败")
# 关闭游标和数据库连接
cursor.close()
db.close()
```
异常处理:
在 pymysql 操作中,常见的异常有:
- `pymysql.err.IntegrityError`:违反了完整性约束条件(例如,主键或唯一键约束)
- `pymysql.err.InternalError`:MySQL 服务器内部错误
- `pymysql.err.ProgrammingError`:SQL 语法错误或参数错误
- `pymysql.err.Warning`:MySQL 服务器产生警告
我们可以使用 try-except 块来捕获这些异常。例如:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = db.cursor()
# 执行SQL语句
sql = "INSERT INTO student(name, age, sex) VALUES ('小明', 18, '男')"
try:
cursor.execute(sql)
db.commit()
print("插入数据成功")
except pymysql.err.IntegrityError:
db.rollback()
print("插入数据失败,违反了完整性约束条件")
except pymysql.err.InternalError:
db.rollback()
print("插入数据失败,MySQL 服务器内部错误")
except pymysql.err.ProgrammingError:
db.rollback()
print("插入数据失败,SQL 语法错误或参数错误")
except pymysql.err.Warning:
print("MySQL 服务器产生警告")
# 关闭游标和数据库连接
cursor.close()
db.close()
```
阅读全文