python用PyMySQL操作mysql数据库
时间: 2023-09-16 07:06:35 浏览: 123
1. 安装PyMySQL
使用pip安装PyMySQL
```
pip install PyMySQL
```
2. 连接数据库
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)
# 创建一个游标对象
cursor = db.cursor()
# 执行SQL语句
cursor.execute('SELECT VERSION()')
# 获取单条数据
data = cursor.fetchone()
print(f'Database version : {data[0]}')
# 关闭游标和数据库连接
cursor.close()
db.close()
```
3. 插入数据
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)
# 创建一个游标对象
cursor = db.cursor()
# 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()
print('插入数据成功')
except:
# 如果发生错误则回滚
db.rollback()
print('插入数据失败')
# 关闭游标和数据库连接
cursor.close()
db.close()
```
4. 查询数据
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)
# 创建一个游标对象
cursor = db.cursor()
# 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(f'first_name={fname},last_name={lname},age={age},sex={sex},income={income}')
except:
print('查询数据失败')
# 关闭游标和数据库连接
cursor.close()
db.close()
```
5. 更新数据
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)
# 创建一个游标对象
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
print('更新数据成功')
except:
# 发生错误时回滚
db.rollback()
print('更新数据失败')
# 关闭游标和数据库连接
cursor.close()
db.close()
```
6. 删除数据
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)
# 创建一个游标对象
cursor = db.cursor()
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (25)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
print('删除数据成功')
except:
# 发生错误时回滚
db.rollback()
print('删除数据失败')
# 关闭游标和数据库连接
cursor.close()
db.close()
```
阅读全文