2022年 11月 13日

python输出数据库_用python如何导出数据库数据

用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自学网!!