代码改变世界

php执行sql文件

2012-08-19 23:57  youxin  阅读(3234)  评论(0)    收藏  举报
<?php
$hostname = 'localhost';
$dbname = 'test';
$username = 'root';
$pw = 'vivian';
$sqlfile = 'gb.sql';
$sql = file_get_contents($sqlfile);
echo($dbname);
echo($sql);
$conn = mysql_connect($hostname,$username,$pw) or die("无法连接数据库");
mysql_select_db($dbname,$conn) or die("无法连接到数据库");
mysql_query($sql) or die(mysql_error());
?>
DROP TABLE IF EXISTS gb_comments;
CREATE TABLE gb_comments(
    cid mediumint(8) NOT NULL AUTO_INCREMENT,
    username char(15) NOT NULL DEFAULT 'zero',
    email char(40),
    website varchar(75),
    passdate datetime NOT NULL,
    title varchar(75) NOT NULL,
    message text NOT NULL,
    PRIMARY KEY (cid)
)TYPE=MyISAM DEFAULT CHARSET=gbk;

sql直接在数据库执行的时候是没有问题的,但是如果是使用php文件执行的话,需要去掉第一行的drop 语句。 
sql执行的时候test数据库是空的,并没有gb_comments.

注意:mysql_query 只能执行一段查询,查询的字串当中不能带分号。如果要执行多个语句,需要将语句分开。

或者用下面的语句:

<?php
$hostname = 'localhost';
$dbname = 'test';
$username = 'root';
$pw = '123456';
$sqlfile = 'gb.sql';
 
$sql = file_get_contents($sqlfile);
echo($dbname);
echo($sql);
$conn = mysql_connect($hostname,$username,$pw) or die("无法连接数据库");
mysql_select_db($dbname,$conn) or die("无法连接到数据库");
 
$ar = split(";",join("",file($sqlfile)));
foreach($ar as $v)
    mysql_query($v);
?>

上面 的代码有一个警告:

Warning: mysqli_query() [function.mysqli-query]: Empty query 

为什么?

因为  类似a;    b   ;

最后一个是空string。

加上 if(!$v)即可。

以上代码循环读取sql文件, 按照;号分割,循环执行每条sql语句。 小点的sql文件可以按照此方法, 太大的文件会很慢, 占用资源很多。

其实还是推荐下面的方法。 调用系统命令去执行, 当然,是有权限去执行命令的。

exec(“mysql.exe -h localhost --user=root --password=mypass -e 'source job_create.sql' ”);

If you are already running mysql, you can execute an SQL script file using the source command or \. command:

mysql> source file_name
mysql> \. file_name