Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute sql file from java

I have an ORACLE SQL sctipt with several queries and tables, and I wan to run that script from my java program at the starting of the program to ensure that everything is on the right place. I found a code to run the script, but it doesn't work for some reason. Can anyone provide me samples so that I can follow it.

This is what I found :

try {
    String line;
    Process p = Runtime.getRuntime().exec ("psql -U sas -d oracle -h @localhost -f Lab_05_Tables.sql");
    BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = input.readLine()) != null) {        
        System.out.println(line);
    }
    input.close();
}
catch (Exception err) {
    err.printStackTrace();
}

But it doesn't work though.

Error

java.io.IOException: Cannot run program "psql": CreateProcess error=2, The system     
cannot find the file specified
like image 476
Sas Avatar asked Nov 29 '11 01:11

Sas


3 Answers

It would be much better, if you have resources, to port SQLs from your script into Java program itself.

See Java JDBC tutorial.

like image 135
Victor Sorokin Avatar answered Oct 19 '22 22:10

Victor Sorokin


You are trying to run external program from your code, which is not a good solution.

If you use Ant, you can use sql task in Ant: http://ant.apache.org/manual/Tasks/sql.html

If you don't use Ant, you should just use the regular jdbc connection.

like image 2
user1070859 Avatar answered Oct 19 '22 20:10

user1070859


It is possible you're running EnterpriseDB Postgres Plus Advanced Server, which would allow you to run Oracle code using psql. The filename "Lab_05_Tables.sql" suggests an educational environment, so forgive me if it seems I'm unduly treating you as a novice.

Before getting this to work in Java, you should get your executed statement to run by itself at the command line.

psql -U sas -d oracle -h @localhost -f Lab_05_Tables.sql

Lots of things may be wrong here and you need to figure that out. Your command line suggests that you are expecting to run the java program on the same server that is running your database server and has the database client installed, and that you're using the user name "sas" to log into a database named "oracle" with no password required. If any of that is not correct then you should find help getting set up on your database before working on your Java app. I would omit the "-h @localhost".

If you're certain all that's working and the scope of your problem is just getting Java to execute your command, then you may just need to add psql to your PATH environment variable.

like image 2
phatfingers Avatar answered Oct 19 '22 20:10

phatfingers