目录
一、前言
本文介绍对MySQL数据库的相关操作,包括获取数据表,导出数据结构,根据自定义设定的条件生成SQL语句,并导出SQL语句,生成的sql文件可用来直接使用,导入到新的数据库中。
数据库:MySQL
开发语言:PHP
前端框架:LayUI
二、效果图
前端页面效果

导出Sql文件

三、实际操作
1、前端代码
包括数据表展示、页面布局、后台请求
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="stylesheet" type="text/css" href="/static/index/layui/css/layui.css">
<script type="text/javascript" src="/static/index/layui/layui.js"></script>
<script src="/static/index/js/jquery-1.11.3.min.js"></script>
<style type="text/css">
body{
background-color:#F7F7F7;
-webkit-overflow-scrolling: touch;
height:auto;
margin:0 auto;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<div style="width:80%; margin: 1rem auto; background: #fff;padding:0.5rem">
<div class="layui-row layui-col-space30">
<div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>数据表</legend>
</fieldset>
<table class="layui-table">
<thead>
<tr>
<th>数据表</th>
</tr>
</thead>
<tbody>
{volist name="tabList" id="vo"}
<tr>
<td>{$vo}</td>
</tr>
{/volist}
</tbody>
</table>
</div>
<div class="layui-col-xs8 layui-col-sm8 layui-col-md8">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>导出数据结构</legend>
</fieldset>
<div class="layui-form-item">
<label class="layui-form-label">输入表名</label>
<div class="layui-input-block">
<input type="text" name="table1" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-normal structure" style="margin-bottom:0.2rem;">导出数据结构</button>
</div>
</div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>导出SQL文件</legend>
</fieldset>
<div class="layui-form-item">
<label class="layui-form-label">输入表名</label>
<div class="layui-input-block">
<input type="text" name="table2" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">字段名</label>
<div class="layui-input-block">
<input type="text" name="field" lay-verify="" autocomplete="off" placeholder="字段" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">表达式</label>
<div class="layui-input-block">
<input type="text" name="expre" lay-verify="" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label" style="color:#999">说明:</label>
<div class="layui-form-mid layui-word-aux"> =;>;<;>=;<=;<>;like;[not]between;[not]in;[not]null</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">查询条件</label>
<div class="layui-input-block">
<input type="text" name="condition" lay-verify="" autocomplete="off" class="layui-input" placeholder="数值或文本">
</div>
<div class="layui-form-mid layui-word-aux"></div>
</div>
<div class="layui-form-item">
<label class="layui-form-label" style="color:#999">说明:</label>
<div class="layui-form-mid layui-word-aux"> 字符串需要加英文引号['字符串'];like需要加%[字符串%];between使用[1 AND 8]形式;in 使用[(1,8)]形式</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-normal creatSql" style="margin-bottom:0.2rem;">生成SQL语句</button>
<button type="button" class="layui-btn layui-btn-normal downSql" style="margin-bottom:0.2rem;">导出sql文件</button>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">原生SQL语句</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea sqltext"></textarea>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
layui.use(['form','element'], function(){
var form = layui.form
,$ = layui.jquery
,element = layui.element;
// 导出数据结构
$('.structure').click(function () {
var table= $("input[name='table1']").val()
console.log(table)
$.ajax({
url:'downStru',
type:'get',
dataType:'JSON',
data:{table:table},
success:function (res) {
console.log(res)
}
})
})
// 导出sql文件
$('.downSql').click(function () {
var table= $("input[name='table2']").val()
console.log(table)
var field= $("input[name='field']").val()
var expre= $("input[name='expre']").val()
var condition= $("input[name='condition']").val()
$.ajax({
url:'downSql',
type:'get',
dataType:'JSON',
data:{table:table,field:field,expre:expre,condition:condition},
success:function (res) {
console.log(res)
}
})
})
// 生成SQL语句
$('.creatSql').click(function () {
var table= $("input[name='table2']").val()
console.log(table)
var field= $("input[name='field']").val()
var expre= $("input[name='expre']").val()
var condition= $("input[name='condition']").val()
$.ajax({
url:'creatSql',
type:'get',
dataType:'JSON',
data:{table:table,field:field,expre:expre,condition:condition},
success:function (res) {
console.log(res)
$('.sqltext').val(res)
}
})
})
})
</script>
</html>
2、获取数据表
获取当前数据库的所有数据表,使用Db类的getTables方法获取数据表,并返回前端页面渲染。
php
public function index()
{
//获取数据库所有的数据表
$tabList = Db::getTables();
$this->assign(['tabList'=>$tabList]);
return $this->fetch();
}
3、导出数据结构
接收前端输入框传过来的参数(要导出来的表名),拼接数据结构的SQL语句,把数据结构的SQL语句写入到文件里,导出。
导出的文件可直接导入数据库,完美衔接。
php
// 导出数据结构
public function downStru()
{
// 接收条件
$table = input('table');
$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名
// 导出数据表结构
$sql = "show create table ".$table;
$res = Db::query($sql);
$info = "-- ----------------------------\r\n";
$info .= "-- Table structure for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
$info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
$sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
// 写入到文件
file_put_contents($to_file_name,$sqlStr);
}

4、生成SQL语句
接收前端传过来的参数:表名、字段名、表达式、查询条件;判断字段名、表达式、查询条件是否为空,根据输入参数组装SQL语句,返回生成的sql语句。
查询条件说明:
- 如果是字符串,需要对字符串加英文引号,如【'字符串'】;
- like需要加%,如【字符串%】;
- between使用【1 AND 8】形式;
- in使用【(1,8)】形式。
php
// 生成SQL语句
public function creatSql()
{
// 接收条件
$table = input('table');
$field = input('field');
$expre = input('expre');
$condition = input('condition');
// 根据输入条件组装查询条件
if (!empty($field) && !empty($expre) && !empty($condition)) {
$where = "where"." ". $field . " " .$expre . " " .$condition;
// 查询语句
$sql = "select * from ".$table ." ".$where;
}else{
// 查询语句
$sql = "select * from ".$table ;
}
return $sql;
}

5、导出SQL文件
① 接收传过来的参数;
② 组装要导出表的数据结构,并写入到文件中
③ 再根据参数条件组装sql语句
④ 组装拼接插入数据格式
⑤ 追加写入到文件中
导出的数据文件可作为数据库迁移或备份,直接导入到新的数据库可直接使用。
php
// 导出sql文件
public function downSql()
{
// ① 接收条件
$table = input('table');
$field = input('field');
$expre = input('expre');
$condition = input('condition');
$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名
/**********② 导出数据表结构**************/
$sql = "show create table ".$table;
$res = Db::query($sql);
$info = "-- ----------------------------\r\n";
$info .= "-- Table structure for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
$info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
$sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
file_put_contents($to_file_name,$sqlStr);
/**********导出数据**************/
// ③ 根据输入条件组装查询条件
if (!empty($field) && !empty($expre) && !empty($condition)) {
$where = "where"." ". $field . " " .$expre . " " .$condition;
// 查询语句
$sql = "select * from ".$table ." ".$where;
}else{
// 查询语句
$sql = "select * from ".$table ;
}
$res = Db::query($sql);
// 判断数据是否为空
if(count($res) >= 1){
$info = "-- ----------------------------\r\n";
$info .= "-- Records for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
file_put_contents($to_file_name,$info,FILE_APPEND);
/**********④ 拼接插入数据格式**************/
foreach($res as $v){
$sqlStr = "INSERT INTO `".$table."` VALUES (";
// 循环出字段对应的数据,并组装
foreach($v as $zd){
// 替换数据中的换行符
$zd = str_replace("\r\n","",$zd);
$sqlStr .= "'".$zd."', ";
}
//去掉最后一个逗号和空格
$sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
$sqlStr .= ");\r\n";
// ⑤ 写入文件
file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
}
file_put_contents($to_file_name,"\r\n",FILE_APPEND);
}
}

四、完整示例
1、前端
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="stylesheet" type="text/css" href="/static/index/layui/css/layui.css">
<script type="text/javascript" src="/static/index/layui/layui.js"></script>
<script src="/static/index/js/jquery-1.11.3.min.js"></script>
<style type="text/css">
body{
background-color:#F7F7F7;
-webkit-overflow-scrolling: touch;
height:auto;
margin:0 auto;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<div style="width:80%; margin: 1rem auto; background: #fff;padding:0.5rem">
<div class="layui-row layui-col-space30">
<div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>数据表</legend>
</fieldset>
<table class="layui-table">
<thead>
<tr>
<th>数据表</th>
</tr>
</thead>
<tbody>
{volist name="tabList" id="vo"}
<tr>
<td>{$vo}</td>
</tr>
{/volist}
</tbody>
</table>
</div>
<div class="layui-col-xs8 layui-col-sm8 layui-col-md8">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>导出数据结构</legend>
</fieldset>
<div class="layui-form-item">
<label class="layui-form-label">输入表名</label>
<div class="layui-input-block">
<input type="text" name="table1" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-normal structure" style="margin-bottom:0.2rem;">导出数据结构</button>
</div>
</div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>导出SQL文件</legend>
</fieldset>
<div class="layui-form-item">
<label class="layui-form-label">输入表名</label>
<div class="layui-input-block">
<input type="text" name="table2" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">字段名</label>
<div class="layui-input-block">
<input type="text" name="field" lay-verify="" autocomplete="off" placeholder="字段" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">表达式</label>
<div class="layui-input-block">
<input type="text" name="expre" lay-verify="" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label" style="color:#999">说明:</label>
<div class="layui-form-mid layui-word-aux"> =;>;<;>=;<=;<>;like;[not]between;[not]in;[not]null</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">查询条件</label>
<div class="layui-input-block">
<input type="text" name="condition" lay-verify="" autocomplete="off" class="layui-input" placeholder="数值或文本">
</div>
<div class="layui-form-mid layui-word-aux"></div>
</div>
<div class="layui-form-item">
<label class="layui-form-label" style="color:#999">说明:</label>
<div class="layui-form-mid layui-word-aux"> 字符串需要加英文引号['字符串'];like需要加%[字符串%];between使用[1 AND 8]形式;in 使用[(1,8)]形式</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-normal creatSql" style="margin-bottom:0.2rem;">生成SQL语句</button>
<button type="button" class="layui-btn layui-btn-normal downSql" style="margin-bottom:0.2rem;">导出sql文件</button>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">原生SQL语句</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea sqltext"></textarea>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
layui.use(['form','element'], function(){
var form = layui.form
,$ = layui.jquery
,element = layui.element;
// 导出数据结构
$('.structure').click(function () {
var table= $("input[name='table1']").val()
console.log(table)
$.ajax({
url:'downStru',
type:'get',
dataType:'JSON',
data:{table:table},
success:function (res) {
console.log(res)
}
})
})
// 导出sql文件
$('.downSql').click(function () {
var table= $("input[name='table2']").val()
console.log(table)
var field= $("input[name='field']").val()
var expre= $("input[name='expre']").val()
var condition= $("input[name='condition']").val()
$.ajax({
url:'downSql',
type:'get',
dataType:'JSON',
data:{table:table,field:field,expre:expre,condition:condition},
success:function (res) {
console.log(res)
}
})
})
// 生成SQL语句
$('.creatSql').click(function () {
var table= $("input[name='table2']").val()
console.log(table)
var field= $("input[name='field']").val()
var expre= $("input[name='expre']").val()
var condition= $("input[name='condition']").val()
$.ajax({
url:'creatSql',
type:'get',
dataType:'JSON',
data:{table:table,field:field,expre:expre,condition:condition},
success:function (res) {
console.log(res)
$('.sqltext').val(res)
}
})
})
})
</script>
</html>
2、后端
php
<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
/**
* 数据库操作类
*/
class Sql extends Controller
{
public function index()
{
//获取数据库所有的数据表
$tabList = Db::getTables();
$this->assign(['tabList'=>$tabList]);
return $this->fetch();
}
// 导出数据结构
public function downStru()
{
// 接收条件
$table = input('table');
$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名
// 导出数据表结构
$sql = "show create table ".$table;
$res = Db::query($sql);
$info = "-- ----------------------------\r\n";
$info .= "-- Table structure for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
$info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
$sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
// 写入到文件
file_put_contents($to_file_name,$sqlStr);
}
// 导出sql文件
public function downSql()
{
// ① 接收条件
$table = input('table');
$field = input('field');
$expre = input('expre');
$condition = input('condition');
$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名
/**********② 导出数据表结构**************/
$sql = "show create table ".$table;
$res = Db::query($sql);
$info = "-- ----------------------------\r\n";
$info .= "-- Table structure for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
$info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
$sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
file_put_contents($to_file_name,$sqlStr);
/**********导出数据**************/
// ③ 根据输入条件组装查询条件
if (!empty($field) && !empty($expre) && !empty($condition)) {
$where = "where"." ". $field . " " .$expre . " " .$condition;
// 查询语句
$sql = "select * from ".$table ." ".$where;
}else{
// 查询语句
$sql = "select * from ".$table ;
}
$res = Db::query($sql);
// 判断数据是否为空
if(count($res) >= 1){
$info = "-- ----------------------------\r\n";
$info .= "-- Records for `".$table."`\r\n";
$info .= "-- ----------------------------\r\n";
file_put_contents($to_file_name,$info,FILE_APPEND);
/**********④ 拼接插入数据格式**************/
foreach($res as $v){
$sqlStr = "INSERT INTO `".$table."` VALUES (";
// 循环出字段对应的数据,并组装
foreach($v as $zd){
// 替换数据中的换行符
$zd = str_replace("\r\n","",$zd);
$sqlStr .= "'".$zd."', ";
}
//去掉最后一个逗号和空格
$sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
$sqlStr .= ");\r\n";
// ⑤ 写入文件
file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
}
file_put_contents($to_file_name,"\r\n",FILE_APPEND);
}
}
// 生成SQL语句
public function creatSql()
{
// 接收条件
$table = input('table');
$field = input('field');
$expre = input('expre');
$condition = input('condition');
// 根据输入条件组装查询条件
if (!empty($field) && !empty($expre) && !empty($condition)) {
$where = "where"." ". $field . " " .$expre . " " .$condition;
// 查询语句
$sql = "select * from ".$table ." ".$where;
}else{
// 查询语句
$sql = "select * from ".$table ;
}
return $sql;
}
}