bcbeer 2020-04-16
一、简介:
MySQL为关系型数据库,其他关系型数据库包括Oracle、DB2、Sql Server等等。Python操作MySQL需要使用到pymsyql模块,pip安装即可。
二、操作MySQL步骤
1、连上数据库(IP、端口号、用户名、密码、数据库名)
2、建立游标
3、执行sql
4、获取结果
5、关闭游标
6、关闭连接
import pymysql
conn = pymysql.connect(
host=‘192.168.1.112‘,
user=‘test‘,
passwd=‘111111‘,
port=3306, # port必须是int类型
db=‘test‘,
charset=‘utf8‘ # charset必须写utf8,不能写utf-8
)
sqla = ‘select * from stu limit 10;‘
sqlb = ‘insert into stu (id,name,sex) VALUE (10000,"张流量","女");‘
cur = conn.cursor() # 建立游标,不指定cursor类型返回的是二维元组
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # 建立游标,指定cursor类型返回的是字典
cur.execute(sqla) # 执行sqla
cur.execute(sqlb) # 执行sqlb
conn.commit() # 执行insert、delete、update语句必须commit
res = cur.fetchall() # 执行所有返回的结果,fetchall返回的是一个二维数组
res = cur.fetchone() # 执行所有返回的结果,fetchone返回的是第一行
res = cur.fetchmany(2) # 执行所有返回的结果,fetchmany传入一个数返回多少条数据
res = cur.description # 返回表中每个字段的信息,description返回的也是一个二维数组
print(res)
cur.close() # 关闭游标
conn.close() # 关闭连接Cursor类型:
不指定cursor类型,即:cur = conn.cursor(),则返回的结果是:((5, ‘Ben‘, 男‘), (6, ‘Lily‘, 女‘)),是一个二维的元组
指定curson类型,即:cur = conn.cursor(cursor=pymysql.cursors.DictCursor),则返回的结果是:
[{‘id‘: 5, ‘name‘: ‘Ben‘, ‘sex‘: ‘男‘}, {‘id‘: 6, ‘name‘: ‘Lily‘, ‘sex‘: ‘女‘}]
fetchall()和fetchone()的区别:
fetchall():获取到这个sql执行的全部结果,它把数据库表中的每一行数据放到一个元组或字典里面
fetchone():获取到这个sql执行的一条结果,它返回的只是一条数据
如果sql语句执行的结果是多条数据的时候,那就用 fetchall(),如果能确定sql执行的结果只有一条,那就用fetchone()
三、封装操作MySQL数据库的函数
def my_db(sql,port=3306,charset=‘utf8‘):
import pymysql
host,user,passwd,db = ‘192.168.1.112‘,‘test‘,‘111111‘,‘test‘ # 定义变量
conn = pymysql.connect(host=host,
user=user,
passwd=passwd,
port=port,
db=db,
charset=charset)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # 建立游标,指定cursor类型返回的是字典
cur.execute(sql) # 执行语句
if sql.strip().split()[0].upper() == ‘SELECT‘: # 判断sql语句是否以select开头
res = cur.fetchall()
else:
conn.commit()
res = ‘OK‘
cur.close() # 关闭游标
conn.close() # 关闭连接
return res四、练习
传入一个表名,把所有数据导出,写入excel文件
def export_excel(table_name):
import pymysql,xlwt
conn = pymysql.connect(
host=‘118.24.3.40‘,
user=‘jxz‘,
passwd=‘123456‘,
port=3306,
db=‘jxz‘,
charset=‘utf8‘)
sql = ‘select * from %s;‘%table_name
cur = conn.cursor() # 建立游标,不指定cursor类型返回的是二维元组
cur.execute(sql) # 执行sql
all_data = cur.fetchall() # 获取表中所有数据
fileds = [filed[0] for filed in cur.description] # 获取表的所有字段存入一个list里面
book = xlwt.Workbook() # 新建一个excel
sheet = book.add_sheet(‘sheet1‘) # 增加sheet页
for col,filed in enumerate(fileds):
sheet.write(0,col,filed) # 将表头写入excel文件中的第一行
row = 1 # 定义行数
for data in all_data: # 控制行
for col,filed in enumerate(data):#控制列
sheet.write(row,col,filed)
row = row + 1 # 每次写完一行,行加1
book.save(‘%s.xls‘%table_name)