OK i know there are lots of questions and articles related to it,and after following them and playing with them still i can't able to succed.Here is my code
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.CodeSource;
import javax.swing.JOptionPane;
public class BackupData
{
public static void main(String[] args) {
try
{
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = BackupData.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
System.out.println("jarDir"+ jarDir);
/*NOTE: Creating Database Constraints*/
String dbName = "xyz";
String dbUser = "root";
String dbPass = "root";
/*NOTE: Creating Path Constraints for folder saving*/
/*NOTE: Here the backup folder is created for saving inside it*/
String folderPath = jarDir + "\\backup";
/*NOTE: Creating Folder if it does not exist*/
File f1 = new File(folderPath);
System.out.println("f1" + f1);
f1.mkdir();
/*NOTE: Creating Path Constraints for backup saving*/
/*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
String savePath = "\"" + jarDir + "\\backup\\" + "1.sql\"";
System.out.println("savepath" + savePath);
/*NOTE: Used to create a cmd command*/
String executeCmd = "C:\\Program Files\\MySQL\\MySQL Workbench 6.3 CE\\mysqldump -u " + dbUser + " -p " + dbPass + " --database " + dbName + " -r " + savePath;
/*NOTE: Executing the command here*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0)
{
System.out.println("Backup Complete");
}
else
{
System.out.println("Backup Failure");
System.out.println(processComplete);
}
}
catch (URISyntaxException | IOException | InterruptedException ex)
{
JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
}
}
}
And the output this code is giving - Backup Failure,2(Process Complete Value)
I just can't understand what am i doing wrong?am i missing something?
I just can't able to figure out that what the problem is,any help will be appreciated,Thanks.
Why do you do all this? There is a command line utility called mysqldump for this purpose.
The mysqldump client utility performs logical backups, producing a set
of SQL statements that can be executed to reproduce the original
database object definitions and table data. It dumps one or more MySQL
databases for backup or transfer to another SQL server. The mysqldump
command can also generate output in CSV, other delimited text, or XML
format. Also you can find the following links useful from mysql
manual.
https://dev.mysql.com/doc/refman/5.7/en/backup-methods.html
https://dev.mysql.com/doc/refman/5.7/en/copying-databases.html
Related
I need to process a high volume of resumes. And want to use this parser:
https://github.com/antonydeepak/ResumeParser
But you run it in powershell with the file to read and the output file.
But I do not know how to automate this, so it read a whole folder containing the resumes.
I know some Java, but cant open the code. Is scripinting in powershell the way to go?
Thanks!
> java -cp '.\bin\*;..\GATEFiles\lib\*;..\GATEFILES\bin\gate.jar;.\lib\*'
code4goal.antony.resumeparser.ResumeParserProgram <input_file> [output_file]
Either make a batch file from an edited directory listing, or write a program.
As this is stackoverflow:
So starting with the same classpath (-cp ...) you can run your own program
public void static main(String[] args) throws IOException {
File[] files = new File("C:/resumes").listFiles();
File outputDir = new File("C:/results");
outputDir.mkDirs();
if (files != null) {
for (File file : files) {
String path = file.getPath();
if (path.endsWith(".pdf")) {
String output = new File(outputDir,
file.getName().replaceFirst("\\.\\w+$", "") + ".json").getPath();
String[] params = {path, output);
ResumeParserProgram.main(params);
// For creating a batch file >x.bat
System.out.println("java -cp"
+ " '.\\bin\\*;..\\GATEFiles\lib\\*;"
+ "..\\GATEFILES\\bin\\gate.jar;.\\lib\\*'"
+ " code4goal.antony.resumeparser.ResumeParserProgram"
+ " \"" + path + "\" \"" + output + "\"");
}
}
}
}
Check that this works, that ResumeParserProgram.main is reenterable.
I'm trying to programmatically import a .sql file into MySQL. The .sql file was generated by mysqldump. I'm trying to do this dynamically in a Java program. But, it keeps failing on the "<" character within Java (I think). If I grab the String in the debugger of the command it's about to run (the "combined" variable below), and paste it into the command line, it works fine. Likewise, when I was trying to get the mysqldump working inside this program, it failed on the ">" character, and I had to replace it with the "--result-file=" argument to get it to work.
String command = mySqlPath + "mysql.exe";
String user = "-u " + settings.dbUser;
String password = "-p" + settings.dbPassword;
String db = settings.dbDatabase;
String inputFile = filePath + mySqlDumpFile;
String combined = command + " " + user + " " + password + " " + db + " < " + inputFile;
ExternalCommandExecuter ece = new ExternalCommandExecuter(combined);
int code = ece.execute();
This results in this String for example
C:\software\mysql5\bin\mysql.exe -u root -p<password>
db_name < C:\software\tomcat7\webapps\ROOT\WEB-INF\documents\dump-1461789460425.sql
Which will result in a exitCode of 1. Pasting it into the command line, and it'll work.
So I couldn't get it to work in Java by importing the file with a "<", instead I had to write an external .sh/.bat file which I call from my Java code.
I get a text file via:
JFileChooser dialog = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Текстовый файл", "txt");
dialog.removeChoosableFileFilter(dialog.getFileFilter());
dialog.addChoosableFileFilter(filter);
dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
dialog.setDialogTitle("Выберите текстовый файл");
dialog.setDialogType(JFileChooser.OPEN_DIALOG);
dialog.setMultiSelectionEnabled(false);
int ret = dialog.showDialog(null, "Открыть");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = dialog.getSelectedFile();
pach = file.getAbsolutePath();
} else return;
System.out.println(pach);
Last command shows:
D:\data\streets.txt
Now I make a request:
try {
querySQL = "LOAD DATA LOCAL INFILE '" + pach + "' INTO TABLE " + DB_NAME + "." + TABLE_NAME + ";";
stSQL.execute(querySQL);
} catch (SQLException e) {
ErrorMsg(e, querySQL);
isError = true;
break;
}
And I do my ErrorMsg issues:
Unable to process the query:
LOAD DATA LOCAL INFILE 'D:\data\streets.txt' INTO TABLE base2.streets;
java.sql.SQLException: Unable to open file 'D:datastreets.txt'for 'LOAD DATA LOCAL INFILE' command.Due to underlying IOException:
Where it removes the skew, and why all this is happening? In fact, if such a request is inserted into Workbench, the query is executed without error. Please tell me the solution of this problem, it is very necessary. Thank you in advance.
P.S. The text is translated into English by Google Translate
You may want to escape the backslashes contained in your path. For you database a backslash ( \ ) can change the value in a way that the string cannot be saved in the database. This can be a problem with other special characters like ' also. Concatenating a string containing ' to you query, adds an additional ' which will break the query.
You can use StringEscapeUtils for doing this. https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html
I have an h2 database, I want generate the sql script and just after that rename this database.
I do something like that
Script.execute("jdbc:h2:" + directory + File.separatorChar + dbName, user, password, file);
Date d = new Date();
Timestamp t = new Timestamp(d.getTime());
File oldfile = new File(directory + File.separatorChar + dbName + ".h2.db");
File newfile = new File(directory + File.separatorChar + t.getTime() + "backup.h2.db");
oldfile.renameTo(newfile)
but rename failed ! I think it's cause Script open my database but how I can close it and rename my file just after ?
Thank's
Solution :
I just add after the Script command, thank's for your help
Connection conn = DriverManager.getConnection("jdbc:h2:" + directory + File.separatorChar + dbName, user, password);
conn.prepareStatement("SHUTDOWN DEFRAG;").execute();
conn.close();
I want to take backup of database. I am using mysql databse and wamp server.For that i have written the following code.
Process runtimeProcess =Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe -u root -pkarma dailyreport -r "+assign+"\\dailyreport.sql");
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0)
{
JOptionPane.showMessageDialog(null, "Backup has been taken successfully", "BackUp", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Could not take backup", "BackUp", JOptionPane.INFORMATION_MESSAGE);
}
In above code String assign denotes the the path where i want to save the backup of database. But problem is that i am taking the location to save backup at runtime.and if I select path where folder name contains space it could not take backup because System does not getting the path as it contains space.Please help me how should i change the runtime.getruntime.exec() command.
Pass the commands in as separate elements in a String array
String[] cmds = new String[] {
"C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe",
"-u",
"root",
"-pkarma",
"dailyreport",
"-r",
assign+"\\dailyreport.sql"};
Process runtimeProcess = Runtime.getRuntime().exec(cmds);
Each element in the array becomes a separate parameter for the command.
Better still, use ProcessBuilder
Enclose the path in double quotes. That would help the shell see the entire argument as a single one instead of multiple arguments due to presence of space.
Process runtimeProcess =
Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql\\mysql5.5.20\\bin\\mysqldump.exe "
+ "-u root -pkarma dailyreport -r \""
+ assign + "\\dailyreport.sql\" ");
Try to put the assign String between quotes:
Process runtimeProcess = Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql"
+ "\\mysql5.5.20\\bin\\mysqldump.exe -u root -pkarma dailyreport "
+ "-r \""+assign+"\"\\dailyreport.sql");