php實現mysql資料庫分表分段備份_php執行個體

來源:互聯網
上載者:User
分卷匯出思路:統計sql語句變數的長度,按1個字元當成1 位元組比較,如果大於設定分卷大小,則寫入一個sql檔案(我也不知道這樣統計是否穩當,這也是借鑒其他的人的)。

分卷匯入思路:按行讀取sql檔案,將每一行當作完整的sql語句存到數組再迴圈執行插入資料庫就可以了,但是在建立表語句分了多行,這個需要單獨處理(就這個花了我好長時間的);

<?php//宋正河 轉載請註明出處set_time_limit(0);header('content-type:text/html;charset=utf-8');mysql_connect('localhost','root','root');mysql_select_db('test');$table_array=get_tables('test');mysql_query('set names utf8');$filesize=1024*1024*4;$start=$_GET['start']?$_GET['start']:0;$part=$_GET['part']?$_GET['part']:'1';$table_index=$_GET['table_index']?$_GET['table_index']:'0';$table=$table_array[$table_index];$num=200000000;//這個數要足夠大,可以是總記錄數$backupdata='';if($start=='0'){$query="SHOW CREATE TABLE `{$table}`";$result = mysql_query($query);$row = mysql_fetch_row($result);$backupdata .= "DROP TABLE IF EXISTS `{$table}`;\n" . $row[1] . ";\n\n";}$limit=($start=='0')?'':" limit $start,$num ";$query="select * from `{$table}` $limit ";$result=mysql_query($query);$numfields = mysql_num_fields($result); //統計欄位數while($row=mysql_fetch_row($result)){$comma = ''; //儲存逗號$backupdata_tmp = "INSERT INTO `{$table}` VALUES (";for($i=0; $i<$numfields; $i++){$backupdata_tmp .= $comma . "'" . mysql_escape_string($row[$i]) . "'";$comma = ',';}$backupdata_tmp .= ");\n";if(strlen($backupdata)+strlen($backupdata_tmp) > $filesize){//寫入檔案並跳轉$file='data/'.$table.'-'.$part.'.sql';file_put_contents($file,$backupdata);echo $file.' 備份完成,程式繼續進行!';$part++;//分段//表名//起點//跳轉sleep(3);echo "";exit;}$backupdata.=$backupdata_tmp;$start++;}if($backupdata){$file='data/'.$table.'-'.$part.'.sql';file_put_contents($file,$backupdata);}echo $table.'備份完成!
';sleep(2);$table_index++;if($table_array[$table_index]){echo "";exit;}else{echo '恭喜你,Database Backup完畢!';}function get_tables($db){$tq = mysql_list_tables($db);while($tr = mysql_fetch_row($tq)){$arrtb[] = $tr[0];}return $arrtb;}?>

以上所述就是本文的全部內容了,希望大家能夠喜歡。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.