如何利用PHP执行.SQL文件


Posted in PHP onJuly 05, 2013

demo.php:

<?php
/**
* 读取 sql 文件并写入数据库
* @version 1.01 demo.php
*/
class DBManager
{
    var $dbHost = '';
    var $dbUser = '';
    var $dbPassword = '';
    var $dbSchema = '';    function __construct($host,$user,$password,$schema)
    {
        $this->dbHost = $host;
        $this->dbUser = $user;
        $this->dbPassword = $password;
        $this->dbSchema = $schema;
    }
    function createFromFile($sqlPath,$delimiter = '(;/n)|((;/r/n))|(;/r)',$prefix = '',$commenter = array('#','--'))
    {
        //判断文件是否存在
        if(!file_exists($sqlPath))
            return false;
        $handle = fopen($sqlPath,'rb');   
        $sqlStr = fread($handle,filesize($sqlPath));
        //通过sql语法的语句分割符进行分割
        $segment = explode(";",trim($sqlStr));
        //var_dump($segment);
        //去掉注释和多余的空行
        foreach($segment as & $statement)
        {
            $sentence = explode("/n",$statement);
            $newStatement = array();
            foreach($sentence as $subSentence)
            {
                if('' != trim($subSentence))
                {
                    //判断是会否是注释
                    $isComment = false;
                    foreach($commenter as $comer)
                    {
                        if(eregi("^(".$comer.")",trim($subSentence)))
                        {
                            $isComment = true;
                            break;
                        }
                    }
                    //如果不是注释,则认为是sql语句
                    if(!$isComment)
                        $newStatement[] = $subSentence;                   
                }
            }
            $statement = $newStatement;
        }
        //对表名加前缀
        if('' != $prefix)
        {
       
            //只有表名在第一行出现时才有效 例如 CREATE TABLE talbeName
            $regxTable = "^[/`/'/"]{0,1}[/_a-zA-Z]+[/_a-zA-Z0-9]*[/`/'/"]{0,1}$";//处理表名的正则表达式
            $regxLeftWall = "^[/`/'/"]{1}";
            $sqlFlagTree = array(
                    "CREATE" => array(
                            "TABLE" => array(
                                    "$regxTable" => 0
                                )
                        ),
                    "INSERT" => array(
                            "INTO" => array(
                                "$regxTable" => 0
                            )
                        )
                    );
            foreach($segment as & $statement)
            {
                $tokens = split(" ",$statement[0]);
                $tableName = array();
                $this->findTableName($sqlFlagTree,$tokens,0,$tableName);
                if(empty($tableName['leftWall']))
                {
                    $newTableName = $prefix.$tableName['name'];
                }
                else{
                    $newTableName = $tableName['leftWall'].$prefix.substr($tableName['name'],1);
                }
                $statement[0] = str_replace($tableName['name'],$newTableName,$statement[0]);
            }
        }       
        //组合sql语句
        foreach($segment as & $statement)
        {
            $newStmt = '';
            foreach($statement as $sentence)
            {
                $newStmt = $newStmt.trim($sentence)."/n";
            }
            $statement = $newStmt;
        }
        //用于测试------------------------       
        //var_dump($segment);
        //writeArrayToFile('data.txt',$segment);
        //-------------------------------
        self::saveByQuery($segment);
        return true;
    }
    private function saveByQuery($sqlArray)
    {
        $conn = mysql_connect($this->dbHost,$this->dbUser,$this->dbPassword);
        mysql_select_db($this->dbSchema);
        foreach($sqlArray as $sql)
        {
            mysql_query($sql);
        }       
        mysql_close($conn);
    }
    private function findTableName($sqlFlagTree,$tokens,$tokensKey=0,& $tableName = array())
    {
        $regxLeftWall = "^[/`/'/"]{1}";
        if(count($tokens)<=$tokensKey)
            return false;       
        if('' == trim($tokens[$tokensKey]))
        {
            return self::findTableName($sqlFlagTree,$tokens,$tokensKey+1,$tableName);
        }
        else
        {
            foreach($sqlFlagTree as $flag => $v)
            {   
                if(eregi($flag,$tokens[$tokensKey]))
                {
                    if(0==$v)
                    {
                        $tableName['name'] = $tokens[$tokensKey];
                        if(eregi($regxLeftWall,$tableName['name']))
                        {
                            $tableName['leftWall'] = $tableName['name']{0};
                        }
                        return true;
                    }
                    else{
                        return self::findTableName($v,$tokens,$tokensKey+1,& $tableName);
                    }
                }
            }
        }
        return false;
    }
}
function writeArrayToFile($fileName,$dataArray,$delimiter="/r/n")
{
    $handle=fopen($fileName, "wb");
    $text = '';
    foreach($dataArray as $data)
    {
        $text = $text.$data.$delimiter;
    }
    fwrite($handle,$text);
}
//测试
$dbM = new DBManager('localhost','w01f','123456','test');
$dbM->createFromFile('data.sql',null,'fff_');
?>

data.sql:
-- phpMyAdmin SQL Dump
-- version 2.11.3
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2008 年 08 月 20 日 12:09
-- 服务器版本: 5.0.51
-- PHP 版本: 5.2.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- 数据库: `newysh`
--
-- --------------------------------------------------------
--
-- 表的结构 `allowed`
--
CREATE TABLE `allowed` (
`bhash` blob NOT NULL,
`bname` varchar(255) character set utf8 NOT NULL,
PRIMARY KEY (`bhash`(20))
) ENGINE=MyISAM DEFAULT CHARSET=gb2312 ROW_FORMAT=DYNAMIC;
--
-- 导出表中的数据 `allowed`
--
-- --------------------------------------------------------
--
-- 表的结构 `allowed_ex`
--
CREATE TABLE `allowed_ex` (
`bhash` blob NOT NULL,
`badded` datetime NOT NULL,
`bsize` bigint(20) unsigned NOT NULL,
`bfiles` int(10) unsigned NOT NULL,
PRIMARY KEY (`bhash`(20))
) ENGINE=MyISAM DEFAULT CHARSET=gb2312 ROW_FORMAT=DYNAMIC;
--
-- 导出表中的数据 `allowed_ex`
--
-- --------------------------------------------------------
--
-- 表的结构 `category`
--
CREATE TABLE `category` (
`cid` int(10) unsigned NOT NULL auto_increment COMMENT '种子分类id',
`name` varchar(255) NOT NULL COMMENT '分类名称,支持html格式',
`sequence` int(10) unsigned NOT NULL COMMENT '显示排序,需要小的排在前面',
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=26 ;
--
-- 导出表中的数据 `category`
--
INSERT INTO `category` (`cid`, `name`, `sequence`) VALUES
(25, '音乐', 23),
(24, '学习资料', 24),
(23, '电影', 25);
-----------------------------------------------------------
注:对于phpmyadmin 生成的sql文件均适用
PHP 相关文章推荐
第1次亲密接触PHP5(2)
Oct 09 PHP
php设计模式 Prototype (原型模式)代码
Jun 26 PHP
教你如何快捷的使用cmd访问mysql小技巧
May 26 PHP
php隐藏IP地址后两位显示为星号的方法
Nov 21 PHP
Symfony页面的基本创建实例详解
Jan 26 PHP
php实现将上传word文件转为html的方法
Jun 03 PHP
php中header设置常见文件类型的content-type
Jun 23 PHP
PHP将Excel导入数据库及数据库数据导出至Excel的方法
Jun 24 PHP
yii2缓存Caching基本用法示例
Jul 18 PHP
PHP实现的链式队列结构示例
Sep 15 PHP
php微信开发之图片回复功能
Jun 14 PHP
详解PHP用mb_string处理windows中文字符
May 26 PHP
PHP session_start()问题解疑(详细介绍)
Jul 05 #PHP
浅析PHP安装扩展mcrypt以及相关依赖项(PHP安装PECL扩展的方法)
Jul 05 #PHP
PHP仿博客园 个人博客(2) 数据库增添改删
Jul 05 #PHP
浅析PHP的ASCII码转换类
Jul 05 #PHP
PHP仿博客园 个人博客(1) 数据库与界面设计
Jul 05 #PHP
PHP cdata 处理(详细介绍)
Jul 05 #PHP
PHP的基本常识小结
Jul 05 #PHP
You might like
PHP 压缩文件夹的类代码
2009/11/05 PHP
PHP中判断变量为空的几种方法小结
2013/11/12 PHP
给ECShop添加最新评论
2015/01/07 PHP
PHP扩展mcrypt实现的AES加密功能示例
2019/01/29 PHP
PHP 实现文件压缩解压操作的方法
2019/06/14 PHP
jQuery中setTimeout的几种使用方法小结
2013/04/07 Javascript
利用js正则表达式验证手机号,email地址,邮政编码
2014/01/23 Javascript
[原创]JQuery 在表单提交之前修改 提交的值
2016/04/14 Javascript
JavaScript数据结构与算法之队列原理与用法实例详解
2017/11/22 Javascript
JS实现生成由字母与数字组合的随机字符串功能详解
2018/05/25 Javascript
在 Vue-CLI 中引入 simple-mock实现简易的 API Mock 接口数据模拟
2018/11/28 Javascript
详解vue 2.6 中 slot 的新用法
2019/07/09 Javascript
js判断在哪个浏览器打开项目的方法
2020/01/21 Javascript
JavaScript Window浏览器对象模型原理解析
2020/05/30 Javascript
javascript实现时间日期的格式化的方法汇总
2020/08/06 Javascript
JS绘图Flot如何实现动态可刷新曲线图
2020/10/16 Javascript
JavaScript canvas实现文字时钟
2021/01/10 Javascript
[13:21]DOTA2国际邀请赛采访专栏:RSnake战队国士无双,Fnatic.Fly
2013/08/06 DOTA
python代码检查工具pylint 让你的python更规范
2012/09/05 Python
python读取文本中数据并转化为DataFrame的实例
2018/04/10 Python
Python高级特性与几种函数的讲解
2019/03/08 Python
Python时间序列处理之ARIMA模型的使用讲解
2019/04/02 Python
Python面向对象实现一个对象调用另一个对象操作示例
2019/04/08 Python
Python3.5 Pandas模块之DataFrame用法实例分析
2019/04/23 Python
Python3 Tkinkter + SQLite实现登录和注册界面
2019/11/19 Python
HTML5-WebSocket实现聊天室示例
2016/12/15 HTML / CSS
店长助理岗位职责
2013/12/13 职场文书
北京大学自荐信范文
2014/01/28 职场文书
先进工作者申报材料
2014/12/23 职场文书
财务会计岗位职责
2015/02/03 职场文书
2015最新学生自我评价范文
2015/03/03 职场文书
民间借贷借条范本
2015/05/25 职场文书
Go 实现英尺和米的简单单位换算方式
2021/04/29 Golang
vue-cli3.x配置全局的scss的时候报错问题及解决
2022/04/30 Vue.js
python数字图像处理数据类型及颜色空间转换
2022/06/28 Python
面试官问我Mysql的存储引擎了解多少
2022/08/05 MySQL