一.背景:
最近在项目上需要定期查询一些sql将数据导出成excrl表格,因此考虑使用python方式处理。
二.安装部署:
1.环境信息
名称 | 版本及地址 |
---|---|
ip地址 | 192.168.3.90 |
DM数据库版本 | DM Database Server x64 V7.6.0.161-Build(2019.05.23-107264)ENT |
python版本 | 建议使用python3 |
dmpython版本 | dmpython 2.3 |
2.部署dmPython,测试连接数据库
1)安装python --提前准备
2)安装DM数据库 --提前准备
安装目录:DM_HOME= /home/dmdba/dmdbms
3)安装DmPython(建议使用Dmpython的源码包,可联系达梦同事提供)
-1-解压安装包
cd /root/python/pyodbc-4.0.30/build/lib.linux-x86_64-2.7
unzip dmPython.zip
cd dmPython
-2-设置环境变量,避免安装报错缺少对应的库文件
export DM_HOME= /home/dmdba/dmdbms
export LD_LIBRARY_PATH=$ LD_LIBRARY_PATH:/root/python/pyodbc-4.0.30/build/lib.linux-x86_64-2.7:/home/dmdba/dmdbms/bin
-3-安装dmPython
cd dmPython
python setup.py install
-4-测试连接数据库
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import dmPython
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 打开数据库连接
conn = dmPython.connect(user='SYSDBA',password='SYSDBA',server='192.168.3.90',port=5236)
# 使用cursor()方法获取操作游标
cur = conn.cursor()
# 如果数据表已经存在使用 execute() 方法删除表。
cur.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 创建数据表SQL语句
sql1 = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cur.execute(sql1)
# 查询A表中的数据
sql2 = ""u"select * from A"""
cur.execute(sql2)
A = cur.fetchone()
#由于有乱码转换字符集
B = [i.decode('utf-8') if isinstance(i, str) else i for i in A]
case_list_righ = str(B).replace('u\'','\'')
print case_list_righ.decode("unicode-escape")
# 关闭数据库连接
conn.close()
3.安装excel用到的模块setuptools-33.1.1 xlwt-1.3.0
下载链接:
链接:https://pan.baidu.com/s/1VsZY_zndVotC5NIEcr9QdA
提取码:1109
解压并安装:
cd setuptools-33.1.1
python setup.py install
cd xlwt-1.3.0
python setup.py install
中间我安装setuptools-33.1.1过程中报错缺少zlib,可先yum install zlib*
4.测试sql语句转为excel
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import dmPython
import xlwt
import datetime
import time
def dm_execute():
# 连接 dm 数据库
conn = dmPython.connect(user='SYSDBA',password='SYSDBA',server='192.168.3.90',port=5236)
curs = conn.cursor()
sql = ''u'select * from A'''
curs.execute(sql)
rows = curs.fetchall()
w = xlwt.Workbook()
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = u"微软雅黑"
style.font = font # 为样式设置字体
sheet_name = 'student' + time.strftime("%Y-%m-%d") #定义sheet名称
filename = 'student_' + time.strftime("%Y-%m-%d") + '.xls' #定义excel名称
ws = w.add_sheet(sheet_name, cell_overwrite_ok=True)
# 将 title 作为 Excel 的列名
title = u"id,name,sex,phone,email,BM_ID"
title = title.split(",")
for i in range(len(title)):
ws.write(0, i, title[i], style)
# # 开始写入数据库查询到的数据
for i in range(len(rows)):
row = rows[i]
for j in range(len(row)):
if row[j]:
item = row[j]
ws.write(i + 1, j, item, style)
# 写文件完成,开始保存xls文件
out_path = '/tmp/student_' + time.strftime("%Y-%m-%d") + '.xls'
w.save(out_path)
conn.close()
return out_path
if __name__ == '__main__':
out_path = dm_execute()
根据该sql会在tmp文件下生成一个名为student+当前日期的excel表格。
更多达梦资讯请上达梦社区了解 https://eco.dameng.com