MySQL database backup/restore with Java Program ?
Hi!
This article is about creating a java program to backup/restore a MySQL database. The article is in two basic parts, namely Backup & Restore.
1. Backup - Basically, the MYSQL command to backup database looks like follows.
1
| mysqldump -u [username] -p[password] -B [dbname] -r [MYSQL file Path] |
The following Code is for the java program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| public class Main{ public void restoreDB(String path){ String executeCmd = "C:/xampp/mysql/bin/mysqldump -u xyz -pxxyyzz -B myDB -r " + path; System.out.println(executeCmd); Process runtimeProcess; try { runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd }); int processComplete = runtimeProcess.waitFor(); System.out.println(processComplete); if(processComplete == 0) { System.out.println("Backup Created Successfully !"); } else { System.out.println("Couldn't Create the backup !"); } } catch(Exception ex) { ex.printStackTrace(); } } public static void main(String[]args){ new Main().restoreDB("C:/File.sql"); }}
2. Restore - Basically, the MYSQL command to restore database looks like follows.
In the query, -u [username] - is where you should type your username to access databases. -p[password] - is where you should type your password to the databases. Then, you should type the name of the database which you need to backup tables to.
Then,Here's a java code to test run this MYSQL command.
Ah, one more thing, You can set path to MYSQL in windows & adjust line 6 as follows.
|
Comments
Post a Comment