首页 > 编程知识 正文

java备份mysql,Java备份数据库通用功能

时间:2023-12-28 11:57:04 阅读:328267 作者:TVRC

本文目录一览:

如何用java程序在linux中备份和还原mysql数据库

将MySql中的数据库导出到文件中 备份import java.io.*;import java.lang.*;public class BeiFen {public static void main(String[] args) {// 数据库导出String user = "root"; // 数据库帐号String password = "root"; // 登陆密码String data...

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("mysqldump").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程序备份和恢复MySql数据库?

java用开源的ssh jar包连接到b服务器执行备份/恢复命令,同样通过命令也可以获取到备份的文件信息,恢复数据库也是一样的,通过命令把文件传输到b服务器,通过命令进行还原

求助,下面的java代码备份mysql数据库,备份的脚本怎么为空?

String user = "root";// 数据库帐号String pwd = "root";// 数据库密码String database = "qlfydb";// 需要备份的数据库名称String filepath = "F:\qlfydb.sql";// 备份的路径地址String stmt = "D:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump " + database + " -h localhost -u " + user+ " -p " + pwd + " --default-character-set=utf8 --result-file="+ filepath;try { Runtime.getRuntime().exec(stmt); System.out.println("数据已经导出到文件"+filepath+"中");} catch (Exception e) { // TODO: handle exception e.printStackTrace();}

如何用Java实现MySQL数据库的备份和恢复

MySQL的一些前台工具是有备份恢复功能的,可是如何在我们的应用程序中实现这一功能呢?本文提供了示例代码来说明如何使用Java代码实现MySQL数据库的备份恢复。

本次实现是使用了MySQL数据库本身提供的备份命令mysqldump和恢复命令mysql,在java代码中通过从命令行调用这两条命令来实现备份和恢复。备份和恢复所使用的文件都是sql文件。

本代码是参照网上某网友提供的源码完成的。

[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数据库的备份与恢复 缺陷:可能会被杀毒软件拦截

*

* @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 + "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();

}

}

}

/**

* 备份数据库,如果指定路径的文件不存在会自动生成

*

* @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备份还原数据库

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

 

public class JavaMysql {

   /*

    * 备份数据库 1、读取配置文件 2、启动智能查询Mysql安装目录 3、备份数据库为sql文件

    */

   public static void backup(String sql) {

 

      Properties pros = getPprVue("prop.properties");

      String username = pros.getProperty("username");

      String password = pros.getProperty("password");

 

      CheckSoftware c = null;

      try {

         System.out.println("MySQL服务安装地址 :"+c.check().toString());

      } catch (Exception e2) {

         e2.printStackTrace();

      }

      String mysqlpaths;

      try {

         mysqlpaths = c.check().toString() + "bin" + "\";

 

         String databaseName = pros.getProperty("databaseName");

         String address = pros.getProperty("address");

         String sqlpath = pros.getProperty("sql");

         File backupath = new File(sqlpath);

         if (!backupath.exists()) {

            backupath.mkdir();

         }

 

         StringBuffer sb = new StringBuffer();

 

         sb.append(mysqlpaths);

         sb.append("mysqldump ");

         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());

         Runtime cmd = Runtime.getRuntime();

         try {

            Process p = cmd.exec(sb.toString());

         } catch (IOException e) {

            e.printStackTrace();

         }

      } catch (Exception e1) {

         e1.printStackTrace();

      }

   }

 

   /*

    * 读取属性文件

    */

   public static Properties getPprVue(String properName) {

 

      InputStream inputStream = JavaMysql.class.getClassLoader()

            .getResourceAsStream(properName);

      Properties p = new Properties();

 

      try {

         p.load(inputStream);

         inputStream.close();

      } catch (IOException e) {

         e.printStackTrace();

      }

 

      return p;

 

   }

 

   /*

    * 根据备份文件恢复数据库

    */

   public static void load(String filename) {

      Properties pros = getPprVue("prop.properties");

      String root = pros.getProperty("jdbc.username");

      String pass = pros.getProperty("jdbc.password");

      String mysqlpaths = c.check().toString() + "bin" + "\";

      String sqlpath = pros.getProperty("sql");

      String filepath = mysqlpaths + sqlpath + filename; // 备份的路径地址

 

      String stmt1 = mysqlpaths + "mysqladmin -u " + root + " -p" + pass

            + " create finacing"; // -p后面加的是你的密码

      String stmt2 = 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 (IOException e) {

         e.printStackTrace();

      }

 

   }

 

   /*

    * Test测试

    */

   public static void main(String[] args) throws IOException {

      backup("2221.sql");

   }

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。