• Post Reply Bookmark Topic Watch Topic
  • New Topic

Execute mysql commands using java program  RSS feed

 
vidya archana
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all....

I want to execute mysql commands using java program.
This is the sample program i wrote.

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.*;

public class ExecLs {

static public void main(String[] args) {
String cmds = "mysql test -u root --password=inapp12 --execute='show tables'";

try {
Process ps = Runtime.getRuntime().exec(cmds);
System.out.print(loadStream(ps.getInputStream()));
System.err.print(loadStream(ps.getErrorStream()));
} catch(IOException ioe) {
ioe.printStackTrace();
}
}

// read an input-stream into a String
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while( (ptr = in.read()) != -1 ) {
buffer.append((char)ptr);
}
return buffer.toString();
}

}


But itis not working..
Instead It displays mysql help..
The same command when tried directly works fine

Pls help....
 
Hari Gangadharan
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you are somehow missing the arguments - maybe it is the fault of the JVM. What I can suggest is to create a program and run that with the same arguments -- it would be easy if it is Unix. You can write a small shell program say test.ksh with the following lines of code:
<code>
#!/usr/bin/bash

echo "Argument Count: $#" >/tmp/xyz
echo "Arguments: $*" >> /tmp/xyz
</code>
Execute "bash test.ksh" followed by your arguments using your Java program and take a look at the /tmp/xyz file. If the arguments did not come through properly, you may need some adjustments. This definitely will give you a hint.

I would also recommend passing the parameter as an array (the other exec method).
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally you would use JDBC and query for the metadata.
Have a look at the java-docs.
But perhaps MySql doesn't support the methods you need - I don't use MySql.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!