search
HomeDatabaseMysql Tutorial详解MYSQL的备份还原(PHP实现)_MySQL

bitsCN.com 手把手教你实现MYSQL的备份还原
示例代码用我比较熟悉的PHP,当然你看完并理解了其中的思路,相信你也可以快速地用你熟悉的语言自己写出来。
一、新建dbBackup类,设置默认参数。

class dbBackup {
    public $host='localhost';    //数据库地址
    public $user='root';    //登录名
    public $pwd='';    //密码
    public $database;    //数据库名
    public $charset='utf8';    //数据库连接编码:mysql_set_charset
}

二、添加数据库连接function。

/**
     * 连接数据库 ...
     */
    function db() {       
        $con = mysql_connect($this->host,$this->user,$this->pwd);
        if (!$con){
            die('Could not connect');
        }

        $db_selected = mysql_select_db($this->database, $con);
        if (!$db_selected) {
            die('Can/'t use select db');
        }

        mysql_set_charset($this->charset);  //设置编码

        return $con;
    }

三、查询数据库表集合

/**
     * 表集合 ...
     */
    function tblist() {
        $list=array();

        $rs=mysql_query("SHOW TABLES FROM $this->database");
        while ($temp=mysql_fetch_row($rs)) {
            $list[]=$temp[0];
        }

        return $list;
    }

四、查询表结构

/**
     * 表结构SQL ...
     */
    function sqlcreate() {
        $sql='';

        $tb=$this->tblist();       
        foreach ($tb as $v) {
            $rs=mysql_query("SHOW CREATE TABLE $v");
            $temp=mysql_fetch_row($rs);
            $sql.="-- 表的结构:{$temp[0]} --/r/n";
            $sql.="{$temp[1]}";
            $sql.=";-- --/r/n/r/n";
        }
        return $sql;
    }

注:$sql.=";-- --/r/n/r/n"; 每句SQL后面必须加上分号(;)分割,MYSQL导入才能识别。-- -- 是程序对SQL语句分割的标识,可以自定义但必须是注释语句,否则影响SQL语句。/r/n无实际意义用于文本美观

五、INSERT INTO语句

/**
     * 数据插入SQL ...
     */
    function sqlinsert() {
        $sql='';

        $tb=$this->tblist();       
        foreach ($tb as $v) {
            $rs=mysql_query("SELECT * FROM $v");
            if (!mysql_num_rows($rs)) {//无数据返回
                continue;
            }       
            $sql.="-- 表的数据:$v --/r/n";
            $sql.="INSERT INTO `$v` VALUES/r/n";       
            while ($temp=mysql_fetch_row($rs)) {
                $sql.='(';
                foreach ($temp as $v2) {
                    if ($v2===null) {
                        $sql.="NULL,";
                    }
                    else {
                        $v2=mysql_real_escape_string($v2);
                        $sql.="'$v2',";
                    }                   
                }
                $sql=mb_substr($sql, 0, -1);
                $sql.="),/r/n";
            }
            $sql=mb_substr($sql, 0, -3);
            $sql.=";-- --/r/n/r/n";   
        }

        return $sql;
    }

注:
1.无数据返回时必须跳出本次循环,避免生成多余代码
2.当字段值为(NULL)时,插入字符为(NULL)而不是('NULL'),没有单引号。3.$v2=mysql_real_escape_string($v2),这是必要的转义
4.mb_substr($sql, 0, -1)、mb_substr($sql, 0, -3),必须去除最后一个逗号(,) 否则SQL语句出错5.$sql.=";-- --/r/n/r/n",详见第四步注

六、备份操作

/**
     * 备份 ...
     * @param $filename 文件路径
     */
    function beifen($filename) {
        $this->db();    //连接数据库

        $sql=$this->sqlcreate();
        $sql2=$this->sqlinsert();       
        $data=$sql.$sql2;

        return file_put_contents($filename, $data);
    }

七、还原操作

/**
     * 还原 ...
     * @param $filename 文件路径
     */
    function huanyuan($filename) {
        $this->db();    //连接数据库

        //删除数据表
        $list=$this->tblist();
        $tb='';
        foreach ($list as $v) {
            $tb.="`$v`,";
        }
        $tb=mb_substr($tb, 0, -1);
        if ($tb) {
            $rs=mysql_query("DROP TABLE $tb");
            if ($rs===false) {
                return false;
            }
        }

        //执行SQL
        $str=file_get_contents($filename);
        $arr=explode('-- --', $str);
        array_pop($arr);

        foreach ($arr as $v) {
            $rs=mysql_query($v);
            if ($rs===false) {
                return false;
            }
        }

        return true;
    }

备份示例:

$x=new dbBackup();
$x->database='test';
$rs=$x->beifen('db.sql');
var_dump($rs);

还原示例:

$x=new dbBackup();
$x->database='test';
$rs=$x->huanyuan('db.sql');
var_dump($rs);

完整代码:

class dbBackup {
    public $host='localhost';    //数据库地址
    public $user='root';    //登录名
    public $pwd='';    //密码
    public $database;    //数据库名
    public $charset='utf8';    //数据库连接编码:mysql_set_charset

    /**
     * 备份 ...
     * @param $filename 文件路径
     */
    function beifen($filename) {
        $this->db();    //连接数据库

        $sql=$this->sqlcreate();
        $sql2=$this->sqlinsert();       
        $data=$sql.$sql2;

        return file_put_contents($filename, $data);
    }

    /**
     * 还原 ...
     * @param $filename 文件路径
     */
    function huanyuan($filename) {
        $this->db();    //连接数据库

        //删除数据表
        $list=$this->tblist();
        $tb='';
        foreach ($list as $v) {
            $tb.="`$v`,";
        }
        $tb=mb_substr($tb, 0, -1);
        if ($tb) {
            $rs=mysql_query("DROP TABLE $tb");
            if ($rs===false) {
                return false;
            }
        }

        //执行SQL
        $str=file_get_contents($filename);
        $arr=explode('-- --', $str);
        array_pop($arr);

        foreach ($arr as $v) {
            $rs=mysql_query($v);
            if ($rs===false) {
                return false;
            }
        }

        return true;
    }

    /**
     * 连接数据库 ...
     */
    function db() {       
        $con = mysql_connect($this->host,$this->user,$this->pwd);
        if (!$con){
            die('Could not connect');
        }

        $db_selected = mysql_select_db($this->database, $con);
        if (!$db_selected) {
            die('Can/'t use select db');
        }

        mysql_set_charset($this->charset);    //设置编码

        return $con;
    }

    /**
     * 表集合 ...
     */
    function tblist() {
        $list=array();

        $rs=mysql_query("SHOW TABLES FROM $this->database");
        while ($temp=mysql_fetch_row($rs)) {
            $list[]=$temp[0];
        }

        return $list;
    }

    /**
     * 表结构SQL ...
     */
    function sqlcreate() {
        $sql='';

        $tb=$this->tblist();       
        foreach ($tb as $v) {
            $rs=mysql_query("SHOW CREATE TABLE $v");
            $temp=mysql_fetch_row($rs);
            $sql.="-- 表的结构:{$temp[0]} --/r/n";
            $sql.="{$temp[1]}";
            $sql.=";-- --/r/n/r/n";
        }
        return $sql;
    }

    /**
     * 数据插入SQL ...
     */
    function sqlinsert() {
        $sql='';

        $tb=$this->tblist();       
        foreach ($tb as $v) {
            $rs=mysql_query("SELECT * FROM $v");
            if (!mysql_num_rows($rs)) {//无数据返回
                continue;
            }       
            $sql.="-- 表的数据:$v --/r/n";
            $sql.="INSERT INTO `$v` VALUES/r/n";       
            while ($temp=mysql_fetch_row($rs)) {
                $sql.='(';
                foreach ($temp as $v2) {
                    if ($v2===null) {
                        $sql.="NULL,";
                    }
                    else {
                        $v2=mysql_real_escape_string($v2);
                        $sql.="'$v2',";
                    }                   
                }
                $sql=mb_substr($sql, 0, -1);
                $sql.="),/r/n";
            }
            $sql=mb_substr($sql, 0, -3);
            $sql.=";-- --/r/n/r/n";   
        }

        return $sql;
    }
}
//备份
//$x=new dbBackup();
//$x->database='test';
//$rs=$x->beifen('db.sql');
//var_dump($rs);
//还原
//$x=new dbBackup();
//$x->database='test';
//$rs=$x->huanyuan('db.sql');
//var_dump($rs);
bitsCN.com

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Is MySQL Beginner-Friendly? Assessing the Learning CurveIs MySQL Beginner-Friendly? Assessing the Learning CurveApr 17, 2025 am 12:19 AM

MySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.

Is SQL a Programming Language? Clarifying the TerminologyIs SQL a Programming Language? Clarifying the TerminologyApr 17, 2025 am 12:17 AM

Yes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper

Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment