项目情况:某单位网站之前是asp开发的,数据库为Access。现在新版网站开发好了,但是数据库是MySQL,现在需要将旧版网站数据导入到新版网站。
思路:按栏目顺序依次读取Access数据库里的数据,插入MySQL数据库。
以下为代码:
$conn = new com("ADODB.Connection");
$connstr="DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".realpath("newasp.mdb");
$conn->Open($connstr);
$rst = new com("ADODB.RecordSet");
$rst->Open("select * from NC_Article where ClassID=86",$conn,1,3);//读取Access库里文章表里栏目ID为86的所有文章
$i = 1;
while(!$rst -> EOF){
$title = iconv("GBK", "UTF-8", $rst -> fields['title']->value);//Access和MySQL编码方式不一样,将取出的数据先转换编码,防止乱码
$author = iconv("GBK", "UTF-8", $rst -> fields['Author']->value);
$source = iconv("GBK", "UTF-8", $rst -> fields['ComeFrom']->value);
$hit = $rst -> fields['AllHits']->value;
$editor = iconv("GBK", "UTF-8", $rst -> fields['Author']->value);
$addtime = strtotime($rst -> fields['WriteTime']->value);
$content = iconv("GBK", "UTF-8", addslashes(str_replace('[InstallDir_ChannelDir]','./Upload/Images/InfoPic/picnews/',$rst -> fields['content']->value)));//替换文章中图片的地址,防止图片链接失效
$filePath = iconv("GBK", "UTF-8", str_replace('UploadPic/','./Upload/Images/InfoPic/picnews/UploadPic/',$rst -> fields['ImageUrl']->value));//替换附件的地址,防止产生无效链接
$sql = "INSERT INTO information(information_title,information_content,information_photo,information_fatherid,information_istop,information_author,information_check1,information_addtime,information_authorid,information_source,information_editor,information_hit) VALUES('$title','$content','$filePath',59,0,'$author',1,$addtime,1,'$source','$editor',$hit)";//将读出的数据全部插入到MySQL库中的文章表(对应的栏目ID为59)
$result = query($sql);
if($result){
echo $i.'添加成功!<br />';
}else{
echo $i.'添加失败!<br />';
}
$rst -> movenext();
$i++;
}
因为旧版网站与新版网站栏目结构略有变更,所以要一个栏目一个栏目地进行迁移,无法一次到位。虽然比较繁琐,但是速度也还快:此单位文章的数据约8000篇左右,栏目数15左右,完成所有数据的迁移时间不到半小时。
注意:读取Access数据PHP需要开启php_pdo_odbc.dll。