首先,設(shè)置mysql的環(huán)境變量(在path中添加%MYSQL_HOME%\bin),重啟電腦。
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比達(dá)日網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式達(dá)日網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋達(dá)日地區(qū)。費(fèi)用合理售后完善,10多年實(shí)體公司更值得信賴。
完整代碼:
備份:
public static void main(String[] args) {
backup();
load();
}
public static void backup() {
try {
Runtime rt = Runtime.getRuntime();
// 調(diào)用 mysql 的 cmd:
Process child = rt
.exec("mysqldump -u root --set-charset=utf8 bjse act_obj");// 設(shè)置導(dǎo)出編碼為utf8。這里必須是utf8
// 把進(jìn)程執(zhí)行中的控制臺輸出信息寫入.sql文件,即生成了備份文件。注:如果不對控制臺信息進(jìn)行讀出,則會導(dǎo)致進(jìn)程堵塞無法運(yùn)行
InputStream in = child.getInputStream();// 控制臺的輸出信息作為輸入流
InputStreamReader xx = new InputStreamReader(in, "utf8");// 設(shè)置輸出流編碼為utf8。這里必須是utf8,否則從流中讀入的是亂碼
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
// 組合控制臺輸出信息字符串
BufferedReader br = new BufferedReader(xx);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
// 要用來做導(dǎo)入用的sql目標(biāo)文件:
FileOutputStream fout = new FileOutputStream(
"e:/mysql-5.0.27-win32/bin/bjse22.sql");
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
writer.write(outStr);
// 注:這里如果用緩沖方式寫入文件的話,會導(dǎo)致中文亂碼,用flush()方法則可以避免
writer.flush();
// 別忘記關(guān)閉輸入輸出流
in.close();
xx.close();
br.close();
writer.close();
fout.close();
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void load() {
try {
String fPath = "e:/mysql-5.0.27-win32/bin/bjse22.sql";
Runtime rt = Runtime.getRuntime();
// 調(diào)用 mysql 的 cmd:
Process child = rt.exec("mysql -u root bjse ");
OutputStream out = child.getOutputStream();//控制臺的輸入信息作為輸出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(fPath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
// 注:這里如果用緩沖方式寫入文件的話,會導(dǎo)致中文亂碼,用flush()方法則可以避免
writer.flush();
// 別忘記關(guān)閉輸入輸出流
out.close();
br.close();
writer.close();
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
備份語句:
mysql SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',
' from db_testtemp where std_state='1';
Query OK, 1 row affected (0.00 sec)
mysql SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',
' from db_testtemp ;
Query OK, 2 rows affected (0.00 sec)
只生成一個(gè)只有數(shù)據(jù)的.txt:SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' lines terminated by '\r\n' from db_testtemp ;
只生成一個(gè)只有數(shù)據(jù)的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --no-create-info --fields-terminated-by=, exam db_testtemp
生成一個(gè)創(chuàng)建數(shù)據(jù)庫語句的.sql,一個(gè)只有數(shù)據(jù)的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --fields-terminated-by=, exam db_testtemp
只生成insert語句:mysqldump -uroot -pncae2010 -w "std_state='1'" -t exam db_testtemp D:\data\a.sql
將MySql中的數(shù)據(jù)庫導(dǎo)出到文件中 備份
import java.io.*;
import java.lang.*;
public class BeiFen {
public static void main(String[] args) {
// 數(shù)據(jù)庫導(dǎo)出
String user = "root"; // 數(shù)據(jù)庫帳號
String password = "root"; // 登陸密碼
String database = "test"; // 需要備份的數(shù)據(jù)庫名
String filepath = "e:\\test.sql"; // 備份的路徑地址
String stmt1 = "mysqldump " + database + " -u " + user + " -p"
+ password + " --result-file=" + filepath;
/*
* String mysql="mysqldump test -u root -proot
* --result-file=d:\\test.sql";
*/
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("數(shù)據(jù)已導(dǎo)出到文件" + filepath + "中");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
將數(shù)據(jù)從磁盤上的文本文件還原到MySql中的數(shù)據(jù)庫
import java.io.*;
import java.lang.*;
/*
* 還原MySql數(shù)據(jù)庫
* */
public class Recover {
public static void main(String[] args) {
String filepath = "d:\\test.sql"; // 備份的路徑地址
//新建數(shù)據(jù)庫test
String stmt1 = "mysqladmin -u root -proot create test";
String stmt2 = "mysql -u root -proot test " + filepath;
String[] cmd = { "cmd", "/c", stmt2 };
try {
Runtime.getRuntime().exec(stmt1);
Runtime.getRuntime().exec(cmd);
System.out.println("數(shù)據(jù)已從 " + filepath + " 導(dǎo)入到數(shù)據(jù)庫中");
} catch (IOException e) {
e.printStackTrace();
}
}
}
MySQL的一些前臺工具是有備份恢復(fù)功能的,可是如何在我們的應(yīng)用程序中實(shí)現(xiàn)這一功能呢?本文提供了示例代碼來說明如何使用Java代碼實(shí)現(xiàn)MySQL數(shù)據(jù)庫的備份恢復(fù)。
本次實(shí)現(xiàn)是使用了MySQL數(shù)據(jù)庫本身提供的備份命令mysqldump和恢復(fù)命令mysql,在java代碼中通過從命令行調(diào)用這兩條命令來實(shí)現(xiàn)備份和恢復(fù)。備份和恢復(fù)所使用的文件都是sql文件。
本代碼是參照網(wǎng)上某網(wǎng)友提供的源碼完成的。
[java] view plaincopy
package xxx.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
/**
* MySQL數(shù)據(jù)庫的備份與恢復(fù) 缺陷:可能會被殺毒軟件攔截
*
* @author xxx
* @version xxx
*/
public class DatabaseBackup {
/** MySQL安裝目錄的Bin目錄的絕對路徑 */
private String mysqlBinPath;
/** 訪問MySQL數(shù)據(jù)庫的用戶名 */
private String username;
/** 訪問MySQL數(shù)據(jù)庫的密碼 */
private String password;
public String getMysqlBinPath() {
return mysqlBinPath;
}
public void setMysqlBinPath(String mysqlBinPath) {
this.mysqlBinPath = mysqlBinPath;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public DatabaseBackup(String mysqlBinPath, String username, String password) {
if (!mysqlBinPath.endsWith(File.separator)) {
mysqlBinPath = mysqlBinPath + File.separator;
}
this.mysqlBinPath = mysqlBinPath;
this.username = username;
this.password = password;
}
/**
* 備份數(shù)據(jù)庫
*
* @param output
* 輸出流
* @param dbname
* 要備份的數(shù)據(jù)庫名
*/
public void backup(OutputStream output, String dbname) {
String command = "cmd /c " + mysqlBinPath + "mysqldump -u" + username
+ " -p" + password + " --set-charset=utf8 " + dbname;
PrintWriter p = null;
BufferedReader reader = null;
try {
p = new PrintWriter(new OutputStreamWriter(output, "utf8"));
Process process = Runtime.getRuntime().exec(command);
InputStreamReader inputStreamReader = new InputStreamReader(process
.getInputStream(), "utf8");
reader = new BufferedReader(inputStreamReader);
String line = null;
while ((line = reader.readLine()) != null) {
p.println(line);
}
p.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (p != null) {
p.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 備份數(shù)據(jù)庫,如果指定路徑的文件不存在會自動生成
*
* @param dest
* 備份文件的路徑
* @param dbname
* 要備份的數(shù)據(jù)庫
*/
public void backup(String dest, String dbname) {
try {
OutputStream out = new FileOutputStream(dest);
backup(out, dbname);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 恢復(fù)數(shù)據(jù)庫
*
* @param input
* 輸入流
* @param dbname
* 數(shù)據(jù)庫名
*/
public void restore(InputStream input, String dbname) {
String command = "cmd /c " + mysqlBinPath + "mysql -u" + username
+ " -p" + password + " " + dbname;
try {
Process process = Runtime.getRuntime().exec(command);
OutputStream out = process.getOutputStream();
String line = null;
String outStr = null;
StringBuffer sb = new StringBuffer("");
BufferedReader br = new BufferedReader(new InputStreamReader(input,
"utf8"));
while ((line = br.readLine()) != null) {
sb.append(line + "/r/n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
writer.flush();
out.close();
br.close();
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 恢復(fù)數(shù)據(jù)庫
*
* @param dest
* 備份文件的路徑
* @param dbname
* 數(shù)據(jù)庫名
*/
public void restore(String dest, String dbname) {
try {
InputStream input = new FileInputStream(dest);
restore(input, dbname);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Configuration config = HibernateSessionFactory.getConfiguration();
String binPath = config.getProperty("mysql.binpath");
String userName = config.getProperty("connection.username");
String pwd = config.getProperty("connection.password");
DatabaseBackup bak = new DatabaseBackup(binPath, userName, pwd);
bak.backup("c:/ttt.sql", "ttt");
bak.restore("c:/ttt.sql", "ttt");
}
}
最后的main方法只是一個(gè)簡單的使用方法的示例代碼。
本人所做的項(xiàng)目是使用了hibernate的,而這里需要提供MySQL的bin路徑和用戶名、密碼,而hibernate.cfg.xml中本身就是需要配置數(shù)據(jù)庫的用戶名和密碼,所以我把MySQL的bin路徑也直接配置到了這個(gè)文件里面,也不需要?jiǎng)?chuàng)建專門的配置文件,不需要寫讀取配置文件的接口了。
如果不明白,可以去看hibernate.cfg.xml的說明,里面是可以配置其他的property的
使用腳本來備份
java中,使用Runtime.exec執(zhí)行腳本
cd C:\PostgreSQL\8.2\bin\clspg_dump -U postgres -d gd_2013 -t gd_cmcc d:\gd_2013_cmcc.backup不寫腳本,直接運(yùn)行,應(yīng)該也是可以的。
文章題目:通過java代碼備份表 java 數(shù)據(jù)庫備份
文章地址:http://sd-ha.com/article20/doijjjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、小程序開發(fā)、網(wǎng)站設(shè)計(jì)公司、App設(shè)計(jì)、網(wǎng)站排名、品牌網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)