operateMySql.py

This commit is contained in:
floraachy 2020-03-26 22:23:40 +08:00
parent 1fc62849de
commit 789bc15a06
1 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,64 @@
"""
=================================
Author: Flora Chen
Time: 2020/3/26 20:09
-_- -_- -_- -_- -_- -_- -_- -_-
=================================
"""
import pymysql
"""
接口base_url: http://api.lemonban.com/futureloan
MySQL数据库连接信息
主机120.78.128.25
port3306
用户future
密码123456
"""
# 第一步:连接数据库
conn = pymysql.connect(host='120.78.128.25',
port=3306,
user='future',
password='123456',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)# 加上这个返回的就是字典
"""
注意
数据库的utf8和utf-8是有区别的
utf8只支持每个字符最多三个字节
utf-8只使用一到四个字节
"""
# 第二步:创建一个游标对象
cur = conn.cursor()
# 第三步执行sql语句
sql = "select * from futureloan.member limit 5" # where reg_name='花儿
res = cur.execute(sql)
print(res) # 打印出来的结果是执行了多少条数据
# 第四步:获取查询到的结果
# fetchone():获取查询到的数据的第一条
data = cur.fetchone()
print(data) # 不加这个cursorclass=pymysql.cursors.DictCursor 返回的是元组
# fetchall():获取查询到的所有数据
datas= cur.fetchall()
print(datas)
# ------------关于增删改sql语句执行的注意点------------
# 增删改sql语句
sql = "insert into......."
cur.execute(sql)
# 第四步: 提交事务
conn.commit()
"""
pymysql操作数据库 默认是开启了事务
所以在执行增删改的相关操作之后一定要提交事务才会生效
连接对象.commit()
"""