【Python + Mysql】之用pymysql库连接Mysql数据库并进行增删改查操作

时间:2021-09-04 22:40:24

用pip下载pymysql并引用

具体请参考文章:

Python之MySQL数据库增删改查操作

python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作》*

Python3利用pymysql操作 MySQL

Python之pymysql的使用》*

python(pymysql)之mysql简单操作

废话不多说,上代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/09/21 09:20
# @Author : zc
# @File : PyMysql.py import pymysql
from datetime import date,datetime,timedelta def connectMysql():
'''connectMysql
连接Mysql数据库
:return: db
'''
# 连接配置信息
config = {
'db' : "ET", # 数据库
'host' : "localhost", # 主机
'port' : 3306, # 端口
'user' : "root", # 用户名
'password' : "" # 密码
} # 创建连接
db = pymysql.connect(**config)
# 返回数据库
return db def selectTable(sql):
'''
# 1.查询操作
:return:查询表et01数据
'''
# 获取操作游标
cur = connectMysql().cursor()
try:
cur.execute(sql) # 执行sql语句
results = cur.fetchall() # 获取查询的所有记录
print("id","name","age","date")
# 遍历结果
for row in results:
et_id = row[0]
et_name = row[1]
et_age = row[2]
et_date = row[3]
# if 0 < et_id < 10:
# print("et_id:" + "0" + str(et_id),
# "et_name:" + et_name,
# "et_age:" + str(et_age),
# "et_date:" + str(et_date))
# else:
# print("et_id:" + str(et_id),
# "et_name:" + et_name,
# "et_age:" + str(et_age),
# "et_date:" + str(et_date))
print("et_id:" + str(et_id),
"et_name:" + et_name,
"et_age:" + str(et_age),
"et_date:" + str(et_date))
except Exception as e:
raise e
print("raise后,会不会执行!") finally:
connectMysql().close() # 关闭连接 def publicMethods(sql,args):
'''
# 2.增、删、改操作
:return:
'''
# 获取操作游标
db = connectMysql()
cur = db.cursor() try:
cur.executemany(sql,args)
# cur.execute(sql, ('zc02', 23, date(2018,9,22))) # 另一种时间写法
#插入多条数据
# cur.executemany(sql, [("tom", "123"), ("alex", '321')])
# 提交
db.commit()
except:
# 错误回滚
connectMysql().rollback()
finally:
cur.close()
connectMysql().close() if __name__ == '__main__':
#1、查询数据库;2、插入数据;3、更新数据;4、删除数据;
num = 1
if num == 1:
# 编写sql查询语句,对应我的表名:et01
sql = "select * from et01;"
selectTable(sql)
elif num == 2:
# 获取明天的时间
tomorrow = datetime.now().date() + timedelta(days=1)
# 插入语句
insert_sql = "insert into et01(et_name,et_age,et_date) values(%s,%s,%s)"
publicMethods(insert_sql,[('zc02',23,tomorrow)])
elif num == 3:
#更新语句
update_sql = "update et01 set et_name = %s where et_id = %s;"
publicMethods(update_sql,[('et01',1)])
elif num == 4:
#删除语句
delete_sql = "delete from et01 where et_id = %s;"
publicMethods(delete_sql,[(3)])