MySQL替换数据库

时间:2015-11-18 10:05:22

标签: php mysql

我有一个.sql文件,想要通过单击按钮替换现有的数据库。一切正常。除了创建查询。是否有任何查询或命令来导入整个数据库?

    $filename = 'file.sql';
    // MySQL host
    $mysql_host = 'localhost';
    // MySQL username
    $mysql_username = 'user';
    // MySQL password
    $mysql_password = 'pw';
    // Database name
    $mysql_database = 'dbName';

    // Connect to MySQL server
    mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
    // Select database
    mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());

    $drop_db = "DROP DATABASE dbName";

    mysql_query($drop_db) or die ("error");

    $create_db = "";

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方式:

$cmds=array_filter( file( $filename ) );
foreach( $cmds as $cmd ){
    echo $cmd;
}

如果看起来不错,请用mysql_query( $cmd )替换回声...完全未经测试的顺便说一句。

    $sql=array();
    $sourcefile='C:\data\db_20101222_0957.sql';

    $cmds = file( $sourcefile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );
    foreach( $cmds as $cmd ){

        if ( substr( $cmd, 0, 2) == '--' || $cmd == '' || substr( $cmd,0, 2)=='/*' ) continue;

        $sql[]=$cmd;

        if ( substr( trim( $cmd ), -1, 1 ) == ';' ){
            /* Query */
            $query=implode( PHP_EOL, $sql );
            /* Execute query */

            echo '<pre>',$query,'</pre>';

            $sql=array();
        }
    }

答案 1 :(得分:1)

我明白了。解决方案是删除表而不是整个数据库。

function resetClient() {
    $erg = false;
    try {
        // get all tablenames
        $sql = "SHOW TABLES FROM dbName";
        $res = $this->conn->query($sql);

        $this->conn->query("SET FOREIGN_KEY_CHECKS=0");

        // drop all tables in db
        if (is_object($res)) {
            if (($res->num_rows > 0)) {
                while ($row = $res->fetch_row()) {
                    $this->conn->query ("DROP TABLE " . $row[0]);
                }
            }
        }

        $this->conn->query("SET FOREIGN_KEY_CHECKS=1");

        //pause
        time_nanosleep(0, 250000000);

        // create tables from script
        $sql = file_get_contents('./scripts/file.sql');
        $this->conn->multi_query($sql);

        $erg = true;

        error_log(date("Y-m-d H:i:s")." - DB resetted\n", 3,
            "./scripts/success.log");
    } catch (Exception $e) {
        // log
        error_log(date("Y-m-d H:i:s")." - DB error\n"
            . "resetClientDB() \n"
            . "Reset error \n"
            . $e->getMessage() . "\n" , 3,
            "./scripts/error.log");
    }
    return $erg;
}