环境:PYTHON2.7,DJANGO1.9.9
urls.py 加一行:
url(r'^mysqldatamanage/', views.mysqldatamanage,name='mysqldatamanage'),
views.py添加对应的方mysqldatamanage,如下:
import std
def mysqldatamanage(request):
if request.method=="POST":
host=request.POST.get("dbip")
dbname=request.POST.get("dbname")
dbuname=request.POST.get("dbuname")
dbpwd=request.POST.get("dbpwd")
if request.POST.has_key('exp'):
try:
sqlstr=request.POST.get("sqlstr")
#print host,ports,dbuname,dbpwd,dbname,sqlstr
filenames=std.exprotmysqltoexcel(host,dbuname,dbpwd,dbname,sqlstr)
except Exception:
return render(request,"manage.html",{"login_err":"FAIL"})
return render(request,"manage.html",{"login_err":"downloadlink:http://IP:8080/"+filenames})
if request.POST.has_key('bak'):
try:
filenames=std.mysqldumpbackup(host,dbuname,dbpwd,dbname)
except Exception:
return render(request,"manage.html",{"login_err":"FAIL"})
return render(request,"manage.html",{"login_err":"downloadlink:http://IP:8080/"+filenames})
else:
return render(request,"manage.html",{"login_err":"no set"})
调用自定义的std.py模块实现如下:
先导入这些模块,有一些是和本次实现没有关联,只是这个模块的其它方法有用到,std.py:
# -*- coding: utf-8 -*-
import sys,re
import os
import subprocess
import datetime
import paramiko
import xlsxwriter
import time
import xlrd
import MySQLdb
import xlwt
#导出到EXCEL的实现
def exprotmysqltoexcel(dbhost,dbuname,dbpwd,dbname,sqlstr):
conn=MySQLdb.connect(host=dbhost,user=dbuname,passwd=dbpwd,db=dbname,charset='utf8')
cursor=conn.cursor()
count = cursor.execute(sqlstr)
cursor.scroll(0,mode='absolute')
results = cursor.fetchall()
fields = cursor.description
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('s1',cell_overwrite_ok=True)
for titles in range(0,len(fields)):
sheet.write(0,titles,fields[titles][0])
rows=1
cols=0
for rows in range(1,len(results)+1):
for cols in range(0,len(fields)):
sheet.write(rows,cols,results[rows-1][cols])
filenames = dbname+time.strftime("%Y-%m-%d-%H-%M-%S")+ ".xls"
wbk.save(".\\files\\"+filenames)
return filenames
#备份到.sql文件的实现
def mysqldumpbackup(dbHost,dbUser,dbPasswd,dbName):
backupDir=".\\files\\"
dbCharset = 'utf8'
backupDate = time.strftime("%Y-%m-%d-%H-%M-%S")
dumppath="D:\\app\\mysql-5.7.23-winx64\\bin\\mysqldump.exe" #mysqldump的路径
os.system(dumppath + " -h%s -u%s -p%s %s --default_character-set=%s > %s/%s_%s.sql" %(dbHost,dbUser,dbPasswd,dbName,dbCharset,backupDir,backupDate,dbName))
filenames = backupDate+"_"+dbName+".sql"
return filenames
前端用到的manage.html文件,前端我不会,随便写的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MYSQLDATAMANAGE</title>
</head>
<body>
<div id="container" class="cls-container">
<div id="bg-overlay" ></div>
<div class="cls-header cls-header-lg">
<div class="cls-brand">
<h3>MYSQLDATAMANAGE</h3>
<h4>MYSQL数据管理</h4>
</div>
</div>
<div class="cls-content">
<div class="cls-content-sm panel">
<div class="panel-body">
<p class="pad-btm">MYSQLDATAMANAGE</p>
<form id="loginForm" action="{% url 'mysqldatamanage' %}" method="POST"> {% csrf_token %}
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<input type="text" class="form-control" name="dbip" placeholder="数据库IP"></br>
<input type="text" class="form-control" name="dbname" placeholder="数据库名"></br>
<input type="text" class="form-control" name="dbuname" placeholder="连接帐号"></br>
<input type="password" class="form-control" name="dbpwd" placeholder="连接密码"></br>
<input type="text" class="form-control" name="sqlstr" placeholder="SQL语句" style="width:300px;height:111px"></br>
</div>
</div>
<button class="btn btn-success btn-block" type="submit" name="bak">
<b>备份</b>
</button>
<button class="btn btn-success btn-block" type="submit" name="exp">
<b>导出到EXCEL</b>
</button>
<h4 style="color: red"><b>{{ login_err }}</b></h4>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
运行效果如下:
点击相应的按钮完成对应的SQL任务,系统返回下载链接,因为我做好了WEB下载目录的配置
除了MYSQL数据库的导出和备份以外,导入和执行SQL等管理任务也可以通过这种方式在WEB端实现,后台的方法如下:
导入的实现:
def importmysqlfromexcel(xlsxunc,dbhost,dbuname,dbpwd,dbname,tablenames):
opxls = xlrd.open_workbook(xlsxunc)
sh = opxls.sheet_by_index(0)
dlist=[]
shrows = sh.nrows #行数
shcols = sh.ncols #列数
fo=[]
fo.append(sh.row_values(0))
for i in range(1,shrows):
dlist.append(sh.row_values(i))
conn=MySQLdb.connect(host=dbhost,user=dbuname,passwd=dbpwd,db=dbname,charset='utf8')
cursor=conn.cursor()
#create table
sqlstr="create table " + tablenames + "("+fo[0][0]+" varchar(100));"
#cursor.execute("create table " +tablenames + " ("+fo[0][0]+" varchar(100));")
cursor.execute(sqlstr)
#UPDATE TABLES
for i in range(1,shcols):
cursor.execute("alter table " +tablenames+" add "+fo[0][i]+" varchar(100);")
val=''
for i in range(0,shcols):
val = val+'%s,'
cursor.executemany("insert into " + tablenames + " values("+val[:-1]+");" ,dlist)
conn.commit()
执行SQL的实现:
def mysqlexecsqlstr(dbHost,dbUser,dbPasswd,dbName,sqlstr):
db = MySQLdb.connect(dbHost,dbUser,dbPasswd,dbName,charset='utf8' )
cursor = db.cursor()
try:
cursor.execute(sqlstr)
db.commit()
except:
db.rollback()
db.close()
和前面一样,前端把参数传递到后台就能实现了