Java backup MySQL
1 Overview
Use java to back up the mysql database, mainly using mysqldump and Runtime (). GetRuntime (). Exec ().
2 create backup path
If there is no backup storage path, create the path first.
Path path = Paths.get (xxxx); try {Files.createDirectories (path);} catch (IOException e) {/ / xxxx} 3 execute the command
If it is executed directly with shell:
Mysqldump-u user_name-p database_name > xxxx\ database_name.sql
Use-u and-p to specify the user and password, respectively, and finally redirect to the file.
However, it should be noted that when using exec () in java, never use the-p option.-p is an interactive password input. The exported file using-p is 0KB and needs to be used.
-- password
Instead of.
String command = "mysqldump-u user-- password=xxxx > xxxx\\ xxxx.sql"
Pay attention to the path problem. In addition, under windows, you need to use cmd:
String command = "cmd / c mysqldump-u user-- password=xxxx > xxxx\\ xxxx.sql"
This needs to be put
% MYSQL_HOME%/bin
Add to the environment variable, and enter the absolute path if you don't:
String command = "cmd / c C:\ Program Files\ mysql\ bin\\ mysqldump-u user-- password=xxxx > xxxx\\ xxxx.sql" 4 execute try {Runtime.getRuntime (). Exec (command);} catch (IOException e) {/ / xxxx} 5 other questions
If there is no exported file or the exported file is 0KB, the possible reason is:
Syntax errors: improper use of command spaces, wrong path settings, wrong parameters, etc. Environmental problems: if the environment variable is not added under windows, "cmd / c" is not added. Wrong username / password: this. Authority problem: the user does not have the corresponding authority, to log in to mysql to authorize.