欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python3實現(xiàn)mysql導(dǎo)出excel的方法

 更新時間:2019年07月31日 14:16:52   作者:路在亻壬走  
這篇文章主要介紹了python3實現(xiàn)mysql導(dǎo)出excel的方法,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值 ,需要的朋友可以參考下

Mysql中'employee'表內(nèi)容如下:

# __Desc__ = 從數(shù)據(jù)庫中導(dǎo)出數(shù)據(jù)到excel數(shù)據(jù)表中
import xlwt
import pymysql
class MYSQL:
  def __init__(self):
    pass
  def __del__(self):
    self._cursor.close()
    self._connect.close()
  def connectDB(self):
    """
    連接數(shù)據(jù)庫
    :return:
    """
    try:
      self._connect = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='test',
        charset='utf8'
      )
      return 0
    except:
      return -1
  def export(self, table_name, output_path):
    self._cursor = self._connect.cursor()
    count = self._cursor.execute('select * from '+table_name)
    # print(self._cursor.lastrowid)
    print(count)
    # 重置游標(biāo)的位置
    self._cursor.scroll(0, mode='absolute')
    # 搜取所有結(jié)果
    results = self._cursor.fetchall()
    # 獲取MYSQL里面的數(shù)據(jù)字段名稱
    fields = self._cursor.description
    workbook = xlwt.Workbook()
    # 注意: 在add_sheet時, 置參數(shù)cell_overwrite_ok=True, 可以覆蓋原單元格中數(shù)據(jù)。
    # cell_overwrite_ok默認(rèn)為False, 覆蓋的話, 會拋出異常.
    sheet = workbook.add_sheet('table_'+table_name, cell_overwrite_ok=True)
    # 寫上字段信息
    for field in range(0, len(fields)):
      sheet.write(0, field, fields[field][0])
    # 獲取并寫入數(shù)據(jù)段信息
    row = 1
    col = 0
    for row in range(1,len(results)+1):
      for col in range(0, len(fields)):
        sheet.write(row, col, u'%s' % results[row-1][col])
    workbook.save(output_path)
if __name__ == '__main__':
  mysql = MYSQL()
  flag = mysql.connectDB()
  if flag == -1:
    print('數(shù)據(jù)庫連接失敗')
  else:
    print('數(shù)據(jù)庫連接成功')
    mysql.export('employee', 'E:/test_input.xls')

執(zhí)行結(jié)果如下:

總結(jié)

以上所述是小編給大家介紹的python3實現(xiàn)mysql導(dǎo)出excel的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

相關(guān)文章

最新評論