tags:

views:

92

answers:

2

How to find the error if the database name not exist in mysql. Database name like demo. I provide this following example code

String dumpCommand = "C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump -h"+hostName+user+demo(//database name);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(dumpCommand);                     
InputStream in = proc.getInputStream();              
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line =null;

 while((line=br.readLine())!=null)
{
//.....
}

This code will run successfully even database name not contains in mysql

A: 

Here are two kinds of errors:

mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect

and

mysqldump: Got error: 1049: Unknown database 'database1name' when selecting the database

Based on that you can do the following

String output = IOUtils.toString(inputStream)
int errIdx = output.indexOf("mysqldump: Got error: ");
if (errIdx != -1) {
   throw new RuntimeException("Failed to perform dump. The error message is: " 
        + output.substring(idx));
}

If you don't want to use IOUtils (from commons-io) you can use your while(..) approach and do the above checks there.

Bozho
Relying on exact wording of error messages should certainly be the very last resort. I don't know, but maybe MySQL has i18n of error messages (or maybe in a future version). In this case, your code would happily except any error message of a non-English installation.
sfussenegger
@sfussenegger since this is calling a command-line program, which (judging by a quick search through the manual) doesn't have i18n, I guess the empirical approach is the only one.
Bozho
As answered by @Rickard, `mysqldump` returns with non-null status in case of error.
sfussenegger
yes, but does this status contain enough information about the error?
Bozho
No, but it is more reliable. After detecting an error, the output of the program could still be used to provide information about the error. But at the end, the question was "How to determine if mysqldump called from Runtime.exec() has failed."
sfussenegger
+1  A: 

After:

Process proc = rt.exec(dumpCommand);

Check the return value, with something like:

if (proc.waitFor() != 0) 
  return;
Rickard von Essen
+1 although silently returning certainly isn't appropriate handling of this situation. But hey, it's your first vote and I don't wanna be too pedantic ;)
sfussenegger
Yes you are right. My answer was more of a hint of how this should be handled. ;)
Rickard von Essen