Backup MYSQL database from a JAVA Application

Below is a simple application to back up your mysql database from a Java application. this post show the GUI of the application and some selected methods that do the job. Hope this will be useful

ma blog

//search for this import on the net

import org.apache.commons.io.FileUtils;

public class dbasebackupdetailpanel extends javax.swing.JPanel {

JFileChooser fc = new JFileChooser();

private boolean isConnected = false;

Connection conn = null;

List tables = null;

String url, password, uname;

//handles the backup button  click

private void btnBackupActionPerformed(java.awt.event.ActionEvent evt) {

try {

fc.setDialogTitle("Create a file to BackUp database");

fc.setCurrentDirectory(fc.getCurrentDirectory());

if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {

File file = new File(fc.getSelectedFile().getAbsolutePath() + ".sql");

String data = null;

if (chkTables.isSelected() == false) {

data = this.getData(tfHost.getText(), tfPort.getValue().toString(), tfUser.getText(), tfPassword.getText(), "dbFStation");

} else {

data = this.getData(tfHost.getText(), tfPort.getValue().toString(), tfUser.getText(), tfPassword.getText(),    "dbFStation",cmbTables.getSelectedItem().toString());

}

FileUtils.writeStringToFile(file, data);//avaible when import org.apache.commons.io.FileUtils;

xputils.showMessage("Backup Successfull");

}

} catch (Exception e) {

xputils.showErrorMessage(e.toString());

}}

//method that handles the connect button

private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {

//validate controls

url = "jdbc:mysql://" + tfHost.getText() + ":" + tfPort.getValue() + "/dbFstation";

uname = tfUser.getText();

password = tfPassword.getText();

try {

conn = DriverManager.getConnection(url, uname, password);

if (conn != null) {

isConnected = true;

this.btnBackup.setEnabled(true);

getTableNames(conn);

this.cmbTables.setModel(tablesModel());

xputils.showMessage("Connection was  Succesfull");

} else {

this.btnBackup.setEnabled(false);

isConnected = false;

xputils.showMessage("Connection was not Succesfull");

}

} catch (SQLException ex) {

Logger.getLogger(dbasebackupdetailpanel.class.getName()).log(Level.SEVERE, null, ex);

}}

private int BUFFER = 10485760;

//method to backup mysql database all tables

private String getData(String host, String port, String user,

String password, String db) throws Exception {

Process run = Runtime.getRuntime().exec(

"mysqldump –host=" + host + " –port=" + port +" –user=" + user + " –password=" + password +    " " +                db);

InputStream in = run.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(in));

StringBuffer content = new StringBuffer();

int count;

char[] cbuf = new char[BUFFER];

while ((count = br.read(cbuf, 0, BUFFER)) != -1) {

content.append(cbuf, 0, count);

}

br.close();

in.close();

return content.toString();

}

//method to backup mysql database –one  table

private String getData(String host, String port, String user,

String password, String db, String table) throws Exception {

Process run = Runtime.getRuntime().exec(

"mysqldump –host=" + host + " –port=" + port +  " –user=" + user + " –password=" + password + " " +                db + "  " + table);

InputStream in = run.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(in));

StringBuffer content = new StringBuffer();

int count;

char[] cbuf = new char[BUFFER];

while ((count = br.read(cbuf, 0, BUFFER)) != -1) {

content.append(cbuf, 0, count);

}

br.close();

in.close();

return content.toString();

}

  //method to retrive table names in mysql

private void getTableNames(Connection con) {

String[] DB_TABLE_TYPES = {"TABLE"};

String COLUMN_NAME_TABLE_NAME = "TABLE_NAME";

ResultSet rs = null;

try {

DatabaseMetaData meta = conn.getMetaData();

rs = meta.getTables(null, null, null, DB_TABLE_TYPES);

if (rs != null) {

tables = new ArrayList();

while (rs.next()) {

String tableName = rs.getString(COLUMN_NAME_TABLE_NAME);

if (tableName != null) {

tables.add(tableName);

}}}

con.close();

} catch (Exception e) {

e.printStackTrace();

}}

//binding a list of tablenames to a comboboxmodel

public ComboBoxModel tablesModel() {

ComboBoxModel model;

if (tables == null || tables.size() <= 0) {

Object[] d = new Object[1];

ComboBoxModel mo = new DefaultComboBoxModel(d);

return mo;

}

Object[] days = new Object[tables.size()];

int i = 0;

try {

ListIterator lg = tables.listIterator();

while (lg.hasNext()) {

days[i] = tables.get(i);

i = i + 1;

}

} catch (Exception ex) {

System.out.println("error occured " + ex.toString());

}

model = new DefaultComboBoxModel(days);

return model;

}

Advertisements

4 thoughts on “Backup MYSQL database from a JAVA Application

  1. Hi,thanks your sharing so i want to ask a question if we want to backup database as using period like daily period or weekly period,how will we this operation?can you give any example related this please.

  2. I wonder if org.apache.commons.io.FileUtils supports 64 bit

    When I execute the example above with my database and other information I get the following incomplete file.
    What can seem to the problem?

    — MySQL dump 10.13 Distrib 5.5.19, for Win64 (x86)

    — Host: localhost Database: �host=localhost
    — ——————————————————
    — Server version 5.5.19

    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
    /*!40101 SET NAMES utf8 */;
    /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
    /*!40103 SET TIME_ZONE=’+00:00′ */;
    /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=’NO_AUTO_VALUE_ON_ZERO’ */;
    /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s