品易云推流 关闭
文章详情页
文章 > Python高级 > 用python如何导出数据库数据

用python如何导出数据库数据

头像

尤及

2020-06-17 15:09:263084浏览 · 0收藏 · 0评论

用python导出数据库数据的方法:

使用“import”命令导入pymysql模块

import pymysql

用connect函数连接数据库,实例化连接对象,调用execute函数将sql语句映射到数据库中

host, user, passwd, db='127.0.0.1','root','123','xxx'
    conn = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8')
cur = conn.cursor()
   
sql = 'select * from %s' % table_name
    
cur.execute(sql)  # 返回受影响的行数

使用fetchall函数就可以导出数据库数据了

fields = [field[0] for field in cur.description]  # 获取所有字段名
    
all_data = cur.fetchall()  # 所有数据

更多Python知识,请关注:Python自学网!!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图