1. 程式人生 > >msql資料備份與還原

msql資料備份與還原

一資料庫備份:

1.將單個表匯出為csv檔案

資料表匯出csv語句:

select *from TSI_20140206_0_20120701 into outfile '/home/maysqldata/TSI_20140206_0_20120701.csv'  fields terminated by ',' optionally enclosed by'"' escaped by '"' lines terminated by '\r\n'; 

資料表匯入csv語句:

匯入的時候需要事先建好表結構,才能夠匯入。

mysql匯出表結構的程式碼:

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

使用mysqldump命令
格式
mysqldump YourDatabaseName -uYourUserName -pYourPassword 
YourDatabaseName是你想處理的資料庫名
YourUserName和YourPassword 對應你的授權口令
如果只需要匯出表的結構,那麼可以使用mysqldump的 -d 選項

匯出整個庫的表結構如下:

mysqldump -uroot -p -d databasename > createtab.sql,

如果只想匯出 表 table1 table2 table3 的 表結構 和 資料呢?
該如何匯出?

mysqldump -uroot -p -d databasename test1 test2 test3 > createtab.sql

-- 上面的是匯出指定表結構,下面這個可以匯出指定表結構和資料
mysqldump -uroot -p --tables databasename > createtab.sql

mysqldump -uroot -p -d databasename table1table2 table3 > createtab.sql

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

然後匯入:

load data infile '/tmp/test.csv' into table test_info  fields terminated by ','  optionally enclosed by '"' escaped by'"' lines terminated by '\r\n';  

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2.當資料表的個數很大,以至於手動備份不方便時(例如將資料庫中所有表匯出為csv檔案),這裡我用了一個比較笨的方法:

首先查詢資料庫中所有的表名,將表名稱輸出為csv檔案。

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA ='BD_result_DB'into outfile '/mnt/80.50store/BD_mysql/BD_result_DB/tableName.csv';;

然後,自己編寫了一個java小程式,讀取這些表名稱,迴圈遍歷生成單表備份語句。

package cn.com.mysqlBack;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public class TestMain {
	public static Logger LOG = Logger.getLogger(TestMain.class);

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ResourceBundle bundle = ResourceBundle.getBundle("config",
				Locale.getDefault());
		String filePath = bundle.getString("inputfile");
		String outfile = bundle.getString("outfile");
		Operate operate = new Operate();
		String sqlDB = "use " + bundle.getString("DB");
		operate.executeQuery(sqlDB);
		String sql = bundle.getString("getTBNameSql");
		operate.executeQuery(sql);
		File file = new File(filePath);
		if (file.isFile() && file.exists()) {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file));
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				String tableBackupSql = "select * from "
						+ lineTxt
						+ " into outfile "
						+ "\'/mnt/80.50store/BD_mysql/"
						+ bundle.getString("DB")
						+ "/"
						+ lineTxt
						+ ".csv\'"
						+ " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' escaped by '\"'  lines terminated by  '\\r\\n';";
				System.out.println(tableBackupSql);
				// String tableBackupSql1
				// ="SELECT * FROM TSI_20140310_320500_0_20120701 INTO OUTFILE '/APP/niuxinzan/123.csv'FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
				// LINES TERMINATED BY '\n';

				// 直接執行sql語句,備份表
				operate.executeQuery(tableBackupSql);
				// 將sql語句儲存到檔案中,以備批量複製到mysql命令列中用。
				System.out.println(tableBackupSql);
				// File outfile1 = new File(outfile);
				// BufferedWriter bw = new BufferedWriter(new
				// FileWriter(outfile1,
				// true));
				// bw.write(tableBackupSql);
				// bw.write("\r\n");
				// bw.flush();
				// bw.close();
			}
			operate.close();
			LOG.info("------out to csv successful!-----");
		}

	}

}

最後將outfile的csv檔案裡面的語句全部複製到mysql命令列中,執行完畢即可。或者,不用複製到mysql命令列,而是直接在程式中執行mysql命令也可。

二資料庫還原

package cn.com.mysqlLoad;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import cn.com.mysqlBack.Operate;
import cn.com.mysqlBack.TestMain;

public class loadCSVToMysql {
	public static Logger LOG = Logger.getLogger(loadCSVToMysql.class);

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		// System.out.println("lines terminated by '\\r\\n';");
		ResourceBundle bundle = ResourceBundle.getBundle("config",
				Locale.getDefault());
		String filePath = bundle.getString("loadinputfile");
		System.out.println("filePath: " + filePath);
		Operate operate = new Operate();
		String sqlDB = "use " + bundle.getString("DBofload");
		System.out.println("sqlDB: " + sqlDB);
		operate.execute(sqlDB);
		File file = new File(filePath);
		if (file.isFile() && file.exists()) {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file));
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				String DROPtable = "";
				String createtable1 = "";
				if (lineTxt.contains("BOTTLENECK")) {
					DROPtable = "DROP TABLE IF EXISTS " + lineTxt;
					createtable1 = "CREATE TABLE "
							+ lineTxt
							..................
							+ " KEY idx_linkID (linkID)) ENGINE=myisam DEFAULT CHARSET=utf8;";

					System.out.println("create table sqlString: "
							+ createtable1);
				}
				if (lineTxt.contains("PASSABLEROUTEDETAIL")) {
					DROPtable = "DROP TABLE IF EXISTS " + lineTxt;
					createtable1 = "CREATE TABLE "
							+ lineTxt
							+ "("
							.............
							+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";
				}
				if (lineTxt.contains("RTIC_INFO")) {
					DROPtable = "DROP TABLE IF EXISTS " + lineTxt;
					createtable1 = "CREATE TABLE "
							.................

					System.out.println("create table sqlString: "
							+ createtable1);
				}
				if (lineTxt.contains("RTIC_ROAD")) {

					DROPtable = "DROP TABLE IF EXISTS " + lineTxt;
					createtable1 = "CREATE TABLE " + lineTxt + "("
							
+..........
+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";System.out.println("create table sqlString: "+ createtable1);}if (lineTxt.contains("RTICLINKINFO")) {DROPtable = "DROP TABLE IF EXISTS " + lineTxt;createtable1 = "CREATE TABLE " + lineTxt + "(".........................+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";System.out.println("create table sqlString: "+ createtable1);}if (lineTxt.contains("TRAFFICVOLUME")) {DROPtable = "DROP TABLE IF EXISTS " + lineTxt;createtable1 = "CREATE TABLE "+ lineTxt............+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";System.out.println("create table sqlString: "+ createtable1);}if (lineTxt.contains("TSI_")) {DROPtable = "DROP TABLE IF EXISTS " + lineTxt;createtable1 = "CREATE TABLE "+ lineTxt+ "("..................+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";System.out.println("create table sqlString: "+ createtable1);}if (lineTxt.contains("user_info")) {DROPtable = "DROP TABLE IF EXISTS " + lineTxt;createtable1 = "CREATE TABLE " + lineTxt + "("+ "id int(11) NOT NULL AUTO_INCREMENT,".............+ ") ENGINE=myisam DEFAULT CHARSET=utf8;";System.out.println("drop table sqlString: " + DROPtable);System.out.println("create table sqlString: "+ createtable1);}operate.execute(DROPtable);operate.execute(createtable1);String tableBackupSql = "load data infile "+ "\'/mnt/80.50store/BD_mysql/"+ bundle.getString("DBofcsv")+ "/"+ lineTxt+ ".csv\'"+ " into table "+ lineTxt+ " fields terminated by ',' optionally enclosed by '\"' escaped by'\"' lines terminated by '\\r\\n';";System.out.println("load table sqlString:" + tableBackupSql);operate.execute(tableBackupSql);}operate.close();LOG.info("------out to csv successful!-----");}}}