java备份
将Mysql中的数据库导出到文件中 备份
import java.io.*;
import java.lang.*;
public class BeiFen {
public static void main(String[] args) {
// 数据库导出
String user = "root"; // 数据库帐号
String password = "root"; // 登陆密码
String database = "test"; // 需要备份的数据库名
String filepath = "e:\\test.sql"; // 备份的路径地址
String stmt1 = "mysqlmp " + database + " -u " + user + " -p"
+ password + " --result-file=" + filepath;
/*
* String mysql="mysqlmp test -u root -proot
* --result-file=d:\\test.sql";
*/
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("数据已导出到文件" + filepath + "中");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
将数据从磁盘上的文本文件还原到MySql中的数据库
import java.io.*;
import java.lang.*;
/*
* 还原MySql数据库
* */
public class Recover {
public static void main(String[] args) {
String filepath = "d:\\test.sql"; // 备份的路径地址
//新建数据库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("数据已从 " + filepath + " 导入到数据库中");
} catch (IOException e) {
e.printStackTrace();
}
}
}
❷ 如何使用java程序备份和恢复MySql数据库
java用开源的ssh jar包连接到b服务器执行备份/恢复命令,同样通过命令也可以获取到备份的文件信息,恢复数据库也是一样的,通过命令把文件传输到b服务器,通过命令进行还原
❸ 怎么用java备份mysql数据库
首先,设置mysql的环境变量(在path中添加%MYSQL_HOME%\bin),重启电脑。
完整代码:
备份:
public static void main(String[] args) {
backup();
load();
}
public static void backup() {
try {
Runtime rt = Runtime.getRuntime();
// 调用 mysql 的 cmd:
Process child = rt
.exec("mysqlmp -u root --set-charset=utf8 bjse act_obj");// 设置导出编码为utf8。这里必须是utf8
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader xx = new InputStreamReader(in, "utf8");// 设置输出流编码为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();
// 要用来做导入用的sql目标文件:
FileOutputStream fout = new FileOutputStream(
"e:/mysql-5.0.27-win32/bin/bjse22.sql");
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
writer.write(outStr);
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
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();
// 调用 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);
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
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)
只生成一个只有数据的.txt:SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' lines terminated by '\r\n' from db_testtemp ;
只生成一个只有数据的.txt:mysqlmp -uroot -pncae2010 -w "std_state='1'" -T D:\data --no-create-info --fields-terminated-by=, exam db_testtemp
生成一个创建数据库语句的.sql,一个只有数据的.txt:mysqlmp -uroot -pncae2010 -w "std_state='1'" -T D:\data --fields-terminated-by=, exam db_testtemp
只生成insert语句:mysqlmp -uroot -pncae2010 -w "std_state='1'" -t exam db_testtemp > D:\data\a.sql
❹ JAVA程序怎样实现Oracle数据库备份和还原
oracle的备份和还原可以用命令行来实现
备份 exp system/manager@TEST file=d:chu.dmp full=y
还原imp system/manager@TEST file=d:chu.dmp
将上面的备份、还原命令可以新建成bat文件。然后在java中可以运行bat文件
Runtime.getRuntime().exec("cmd.exe/CstartD:\test.bat");
这样就实现了oracle的备份与还原。当然这里只是提供一个大概的思路,实际运用中可能需要备份某些数据,还原到其他数据库等。
❺ 怎样使用java代码实现数据库表的自动备份
将MySql中的数据库导出到文件中 备份
import java.io.*;
import java.lang.*;
public class BeiFen {
public static void main(String[] args) {
// 数据库导出
String user = "root"; // 数据库帐号
String password = "root"; // 登陆密码
String database = "test"; // 需要备份的数据库名
String filepath = "e:\\test.sql"; // 备份的路径地址
String stmt1 = "mysqlmp " + database + " -u " + user + " -p"
+ password + " --result-file=" + filepath;
/*
* String mysql="mysqlmp test -u root -proot
* --result-file=d:\\test.sql";
*/
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("数据已导出到文件" + filepath + "中");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
将数据从磁盘上的文本文件还原到MySql中的数据库
import java.io.*;
import java.lang.*;
/*
* 还原MySql数据库
* */
public class Recover {
public static void main(String[] args) {
String filepath = "d:\\test.sql"; // 备份的路径地址
//新建数据库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("数据已从 " + filepath + " 导入到数据库中");
} catch (IOException e) {
e.printStackTrace();
}
}
}
❻ 如何用Java实现MySQL数据库的备份和恢复
直接黏贴在IDEA上按格式查看
package com.liuzy.javaopen.servlet;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;public class Test { public static void main(String[] args) throws IOException{ backup("d:\\d.sql"); //recover("d:\\d.sql"); } public static void backup(String path) throws IOException{ Runtime runtime = Runtime.getRuntime(); //-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字 Process process = runtime.exec("mysqlmp -u root -pmysql goldenwing"); InputStream inputStream = process.getInputStream();//得到输入流,写成.sql文件 InputStreamReader reader = new InputStreamReader(inputStream); BufferedReader br = new BufferedReader(reader); String s = null; StringBuffer sb = new StringBuffer(); while((s = br.readLine()) != null){ sb.append(s+"\r\n"); } s = sb.toString(); System.out.println(s); File file = new File(path); file.getParentFile().mkdirs(); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(s.getBytes()); fileOutputStream.close(); br.close(); reader.close(); inputStream.close(); } public static void recover(String path) throws IOException{ Runtime runtime = Runtime.getRuntime(); //-u后面是用户名,-p是密码-p后面最好不要有空格,-family是数据库的名字,--default-character-set=utf8,这句话一定的加 //我就是因为这句话没加导致程序运行成功,但是数据库里面的内容还是以前的内容,最好写上完成的sql放到cmd中一运行才知道报错了 //错误信息: //mysql: Character set 'utf-8' is not a compiled character set and is not specified in the ' //C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\Index.xml' file ERROR 2019 (HY000): Can't // initialize character set utf-8 (path: C:\Program Files\MySQL\MySQL Server 5.5\share\charsets\), //又是讨人厌的编码问题,在恢复的时候设置一下默认的编码就可以了。 Process process = runtime.exec("mysql -u root -pmysql --default-character-set=utf8 goldenwing"); OutputStream outputStream = process.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path))); String str = null; StringBuffer sb = new StringBuffer(); while((str = br.readLine()) != null){ sb.append(str+"\r\n"); } str = sb.toString(); System.out.println(str); OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8"); writer.write(str); writer.flush(); outputStream.close(); br.close(); writer.close(); }}
❼ 如何用Java实现MySQL数据库的备份和恢复
MySQL的一些前台工具是有备份恢复功能的,可是如何在我们的应用程序中实现这一功能呢?本文提供了示例代码来说明如何使用Java代码实现MySQL数据库的备份恢复。
本次实现是使用了MySQL数据库本身提供的备份命令mysqlmp和恢复命令mysql,在java代码中通过从命令行调用这两条命令来实现备份和恢复。备份和恢复所使用的文件都是sql文件。
本代码是参照网上某网友提供的源码完成的。
[java] view plain
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数据库的备份与恢复 缺陷:可能会被杀毒软件拦截
*
* @author xxx
* @version xxx
*/
public class DatabaseBackup {
/** MySQL安装目录的Bin目录的绝对路径 */
private String mysqlBinPath;
/** 访问MySQL数据库的用户名 */
private String username;
/** 访问MySQL数据库的密码 */
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;
}
/**
* 备份数据库
*
* @param output
* 输出流
* @param dbname
* 要备份的数据库名
*/
public void backup(OutputStream output, String dbname) {
String command = "cmd /c " + mysqlBinPath + "mysqlmp -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();
}
}
}
/**
* 备份数据库,如果指定路径的文件不存在会自动生成
*
* @param dest
* 备份文件的路径
* @param dbname
* 要备份的数据库
*/
public void backup(String dest, String dbname) {
try {
OutputStream out = new FileOutputStream(dest);
backup(out, dbname);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 恢复数据库
*
* @param input
* 输入流
* @param dbname
* 数据库名
*/
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();
}
}
/**
* 恢复数据库
*
* @param dest
* 备份文件的路径
* @param dbname
* 数据库名
*/
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方法只是一个简单的使用方法的示例代码。
本人所做的项目是使用了hibernate的,而这里需要提供MySQL的bin路径和用户名、密码,而hibernate.cfg.xml中本身就是需要配置数据库的用户名和密码,所以我把MySQL的bin路径也直接配置到了这个文件里面,也不需要创建专门的配置文件,不需要写读取配置文件的接口了。
如果不明白,可以去看hibernate.cfg.xml的说明,里面是可以配置其他的property的
❽ javaweb如何备份数据库
类JavaMysql备份还原数据库
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
publicclassJavaMysql{
/*
*备份数据库1、读取配置文件2、启动智能查询Mysql安装目录3、备份数据库为sql文件
*/
publicstaticvoidbackup(Stringsql){
Propertiespros=getPprVue("prop.properties");
Stringusername=pros.getProperty("username");
Stringpassword=pros.getProperty("password");
CheckSoftwarec=null;
try{
System.out.println("MySQL服务安装地址:"+c.check().toString());
}catch(Exceptione2){
e2.printStackTrace();
}
Stringmysqlpaths;
try{
mysqlpaths=c.check().toString()+"bin"+"\";
StringdatabaseName=pros.getProperty("databaseName");
Stringaddress=pros.getProperty("address");
Stringsqlpath=pros.getProperty("sql");
Filebackupath=newFile(sqlpath);
if(!backupath.exists()){
backupath.mkdir();
}
StringBuffersb=newStringBuffer();
sb.append(mysqlpaths);
sb.append("mysqlmp");
sb.append("--opt");
sb.append("-h");
sb.append(address);
sb.append("");
sb.append("--user=");
sb.append(username);
sb.append("");
sb.append("--password=");
sb.append(password);
sb.append("");
sb.append("--lock-all-tables=true");
sb.append("--result-file=");
sb.append(sqlpath);
sb.append(sql);
sb.append("");
sb.append("--default-character-set=utf8");
sb.append(databaseName);
System.out.println("cmd指令:"+sb.toString());
Runtimecmd=Runtime.getRuntime();
try{
Processp=cmd.exec(sb.toString());
}catch(IOExceptione){
e.printStackTrace();
}
}catch(Exceptione1){
e1.printStackTrace();
}
}
/*
*读取属性文件
*/
(StringproperName){
InputStreaminputStream=JavaMysql.class.getClassLoader()
.getResourceAsStream(properName);
Propertiesp=newProperties();
try{
p.load(inputStream);
inputStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
returnp;
}
/*
*根据备份文件恢复数据库
*/
publicstaticvoidload(Stringfilename){
Propertiespros=getPprVue("prop.properties");
Stringroot=pros.getProperty("jdbc.username");
Stringpass=pros.getProperty("jdbc.password");
Stringmysqlpaths=c.check().toString()+"bin"+"\";
Stringsqlpath=pros.getProperty("sql");
Stringfilepath=mysqlpaths+sqlpath+filename;//备份的路径地址
Stringstmt1=mysqlpaths+"mysqladmin-u"+root+"-p"+pass
+"createfinacing";//-p后面加的是你的密码
Stringstmt2=mysqlpaths+"mysql-u"+root+"-p"+pass
+"finacing<"+filepath;
String[]cmd={"cmd","/c",stmt2};
try{
Runtime.getRuntime().exec(stmt1);
Runtime.getRuntime().exec(cmd);
System.out.println("数据已从"+filepath+"导入到数据库中");
}catch(IOExceptione){
e.printStackTrace();
}
}
/*
*Test测试
*/
publicstaticvoidmain(String[]args)throwsIOException{
backup("2221.sql");
}
}
❾ java 备份mysql数据库
备份MySQL数据库的方法:
import java.io.File;
import java.io.IOException;
/**
* MySQL数据库备份
*
* @author GaoHuanjie
*/
public class MySQLDatabaseBackup {
/**
* Java代码实现MySQL数据库导出
*
* @author GaoHuanjie
* @param hostIP MySQL数据库所在服务器地址IP
* @param userName 进入数据库所需要的用户名
* @param password 进入数据库所需要的密码
* @param savePath 数据库导出文件保存路径
* @param fileName 数据库导出文件文件名
* @param databaseName 要导出的数据库名
* @return 返回true表示导出成功,否则返回false。
*/
public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 如果目录不存在
saveFile.mkdirs();// 创建文件夹
}
if (!savePath.endsWith(File.separator)) {
savePath = savePath + File.separator;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqlmp").append(" --opt").append(" -h").append(hostIP);
stringBuilder.append(" --user=").append(userName) .append(" --password=").append(password).append(" --lock-all-tables=true");
stringBuilder.append(" --result-file=").append(savePath + fileName).append(" --default-character-set=utf8 ").append(databaseName);
try {
Process process = Runtime.getRuntime().exec(stringBuilder.toString());
if (process.waitFor() == 0) {// 0 表示线程正常终止。
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws InterruptedException {
if (exportDatabaseTool("172.16.0.127", "root", "123456", "D:/backupDatabase", "2014-10-14.sql", "test")) {
System.out.println("数据库备份成功!!!");
} else {
System.out.println("数据库备份失败!!!");
}
}
}
❿ java备份postgresql
使用脚本来备份
java中,使用Runtime.exec执行脚本
cd C:\PostgreSQL\8.2\bin\clspg_mp -U postgres -d gd_2013 -t gd_cmcc > d:\gd_2013_cmcc.backup不写脚本,直接运行,应该也是可以的。