zoukankan      html  css  js  c++  java
  • php导入sql文件

    基本思路:

    1.打开sql文件,放入一个变量(字符串类型)当中

    2.使用正则替换掉当中的注释(“--”与“/**/”)

    3.使用explode分割成为一个数组并去除每行的空格

    4.链接数据库之后使用my_query()执行sql

    <?php
    
    class ReadSql {
    
        //数据库连接
        protected $connect = null;
        //数据库对象
        protected $db = null;
        //sql文件
        public $sqlFile = "";
        //sql语句集
        public $sqlArr = array();
    
        public function __construct($host, $user, $pw, $db_name) {
            $host = empty($host) ? C("DB_HOST") : $host;
            $user = empty($user) ? C("DB_USER") : $user;
            $pw = empty($pw) ? C("DB_PWD") : $pw;
            $db_name = empty($db_name) ? C("DB_NAME") : $db_name;
            //连接数据库
            $this->connect = mysql_connect($host, $user, $pw) or die("Could not connect: " . mysql_error());
            $this->db = mysql_select_db($db_name, $this->connect) or die("Yon can not select the table:" . mysql_error());
        }
    
        //导入sql文件
        public function Import($url) {
    
            $this->sqlFile = file_get_contents($url);
            if (!$this->sqlFile) {
                exit("打开文件错误");
            } else {
                $this->GetSqlArr();
                if ($this->Runsql()) {
                    return true;
                }
            }
        }
    
        //获取sql语句数组
        public function GetSqlArr() {
            //去除注释
            $str = $this->sqlFile;
            $str = preg_replace('/--.*/i', '', $str);
            $str = preg_replace('/\/\*.*\*\/(\;)?/i', '', $str);
            //去除空格 创建数组
            $str = explode(";\n", $str);
            foreach ($str as $v) {
                $v = trim($v);
                if (empty($v)) {
                    continue;
                } else {
                    $this->sqlArr[] = $v;
                }
            }
        }
    
        //执行sql文件
        public function RunSql() {
    
            foreach ($this->sqlArr as $k => $v) {
                if (!mysql_query($v)) {
                    exit("sql语句错误:第" . $k . "行" . mysql_error());
                }
            }
            return true;
        }
    
    }
    
    //范例:
    header("Content-type:text/html;charset=utf-8");
    $sql = new ReadSql("localhost", "root", "", "log_db");
    $rst = $sql->Import("./log_db.sql");
    if ($rst) {
       echo "Success!";
    }
    ?>

    希望对你有所帮助!^_^~

  • 相关阅读:
    cocos2d-x 2.2 study ------------------------ 双击事件(转)
    cocos2d-x打包Android
    cocos2d-x在win7下的android交叉编译环境
    Cocos2d-x之CCImage深入分析
    Eclipse开发C/C++之使用技巧小结
    TortoiseSVN安装使用
    cocos2d-x 2.2 study ------------------------ CCCallFunC家族
    cocos2d-x改底层之动态改变UIListView中的某项在链表中的位置
    汇编语言,以10进制的方式显示数字
    JVM
  • 原文地址:https://www.cnblogs.com/longdidi/p/2951830.html
Copyright © 2011-2022 走看看