2

I am trying to import database from .sql file in postgres using "\i E:/dump.sql" command , its working fine from postgres command prompt but when i try the same from java it raise an error at "\" , my code is

connection = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/database","postgres", "passwd");
PreparedStatement ps3 = connection.prepareStatement("\\i E:/dump.sql");
boolean res3= ps3.execute();
System.out.println("imported succesfully .."+res3);
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55

2 Answers2

3

With the JDBC driver/interface you can only talk SQL, what you're trying is to issue PostgreSQL commandline tool (psql) specific commands. That won't work.

If you insist on doing this, you could use the Runtime.getRuntime().exec(...) approach, something like

Runtime.getRuntime().exec( "psql -f dump.sql" );

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
  • thanks for the answer , how i can do the same with Runtime.getRuntime().exec() ..can you please elaborate it. – Mohammed Anwar Jul 04 '13 at 11:51
  • 1
    Here on Stackoverflow you are expected to show some effort yourself. There are tons of resources on this matter here and elsewhere. – Anders R. Bystrup Jul 04 '13 at 11:54
  • it doesn't work dude , becoz with "psql -f dump.sql" it will prompt you for password . how i would provide that ? .. ok . i will be managing that using ProcessBuilder and its environment() method . but still its raising error path specified not found . just stucked! – Mohammed Anwar Jul 05 '13 at 06:53
  • Look at [this post](http://stackoverflow.com/questions/6523019/postgresql-scripting-psql-execution-with-password) or setup trust in `pg_hba.conf` – Anders R. Bystrup Jul 05 '13 at 06:58
1

Long story short - you can't. \i is not PostgreSQL command (as in: PostgreSQL database engine). It's command of psql - which is command line tool for interacting with database.

If you're connecting to database via JDBC you're not using psql, so you can't use its commands (\i, \o and alike).

  • sure, open the file, read ot, oarse into separate queries, and send them to pg. or use psql, like Anders suggested. –  Jul 05 '13 at 09:24