HTML HTML5 PHP Mysql Linux 缓存技术 工具 资讯 读书 其他
当前位置: 资讯首页 » 全文内容

导出mysql生成sql语句

发布于: 2018-03-30 06:46:14 )
<?php

function query($sql, $dbname = '') {
    $dbConf = array(
        'host'     => '127.0.0.1',
        'user'     => 'user',
        'password' => 'pwd',
        'port'     => 3306,
    );
    $ret         = array();
    $db          = mysqli_connect($dbConf['host'], $dbConf['password'], $dbConf['password'], $dbname, $dbConf['port']);
    $retry_times = 20;
    while (mysqli_connect_errno()) {
        sleep(1);
        $db          = mysqli_connect($dbConf['host'], $dbConf['password'], $dbConf['password'], $dbname, $dbConf['port']);
        if ($retry_times-- <= 0) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit(1);
        }
    }
    if ($result = mysqli_query($db, $sql)) {
        while ($row = mysqli_fetch_assoc($result)) {
            $ret[] = $row;
        }
    }

    return $ret;
}

function write_file($name = 'tblCourse', $content) {
    $dirPath = '/path';
    if (!is_dir($dirPath)) {
        mkdir($dirPath);
    }

    $content = $content . "\n";
    file_put_contents($dirPath . "/" . $name.'.sql', $content, FILE_APPEND);
}

$dbName = 'database_name';
$tableName = 'talbe_name';
$filterId = 'id';

$fileds = '`id`';

$sqlInsert = "INSERT INTO {$tableName} ({$fileds}) VALUES "; 
$lastId   = 0;
$pageSize = 1000;

do {
    $sql  = "select * from {$tableName} WHERE $filterId > $lastId order by $filterId asc limit $pageSize";
    $list = query_fudao($sql, $dbName);

    if (!empty($list)) {
        $batchSql = '';
        foreach ($list as $item) {
            $itemT = array_map('addslashes',$item);
            $sqltmp   = implode("','", $itemT);
            $sqltmp   = "('" . $sqltmp . "'),";
            $batchSql .= $sqltmp;
        }
        $batchSql = $sqlInsert . $batchSql;
        $sql      = rtrim($batchSql, ',') . ';';
        write_file($tableName, $sql);
        $lastId = $item[$filterId];
	usleep(500);
    } else {
        $lastId = 0;
    }
} while ($lastId > 0);
To Top