sql文件怎么用php导入到数据库

sql文件怎么用php导入到数据库,第1张

<?php

$file_name = "d:test.sql"

$dbhost = "localhost"

$dbuser = "root"

$dbpass = "123456"

$dbname = "test"

set_time_limit(0)

$fp = @fopen($file_name,"r") or die("sql文件打不开")//打开文件

$pdo = new PDO("mysql:host=localhostdbname=test","root","123456")//连接数据库

$pdo->query('set names utf8')//设置编码

echo "正在执行导入 *** 作"

while($SQL = GetNextSQL()){

if(!$pdo->query($SQL)){

echo "执行出错"

echo "SQL语句为".$SQL

}

}

echo "导入完成"

fclose($fp) or die("can't close file")//关闭文件

mysql_close()

//从文件中逐条取sql

function GetNextSQL(){

global $fp

$sql=""

while($line = @fgets($fp,40960)){

$line = trim($line)

$line = str_replace("////", "//", $line)

$line = str_replace("/","'",$line)

$line = str_replace("//r//n","chr(13).chr(10)",$line)

$line = stripcslashes($line)

if(strlen($line)>1){

if($line[0]=='-' &&$line[1]=="-"){

continue

}

}

$sql .= $line.chr(13).chr(10)

if(strlen($line)>0){

if($line[strlen($line)-1]==""){

break

}

}

}

return $sql

}

亲测有效。。

需要PHP基础知识和数据库基础知识。

以SQL为例。使用PHP MySQL 函数可以编辑数据库。

mysql_connect() 函数打开MySQL 连接。举例

<?php

$con = mysql_connect("localhost","mysql_user","mysql_pwd")

if (!$con)

{

die('Could not connect: ' . mysql_error())

}// 一些代码...mysql_close($con)

?>

mysql_connect()三个参数分别是服务器名,连接账号,连接密码。

连接之后,可以使用mysql_select_db()设置要处理的数据库,后面则是用数据库语句处理数据。SQL语法简介网页链接

点击MySQL管理器--》点击进入MySQL-Front--》在localhost下选择新建一个数据库--》点击新建数据库后,在对象浏览器窗口,单击右键--》输入--》sql文件命令,进入后选择对应.sql文件进行导入(注意:字符集格式选择


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/10772584.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-11
下一篇 2023-05-11

发表评论

登录后才能评论

评论列表(0条)

保存