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);

2 Answers 2

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,

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the answer , how i can do the same with Runtime.getRuntime().exec() ..can you please elaborate it.
Here on Stackoverflow you are expected to show some effort yourself. There are tons of resources on this matter here and elsewhere.
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!
Look at this post or setup trust in pg_hba.conf
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).

1 Comment

sure, open the file, read ot, oarse into separate queries, and send them to pg. or use psql, like Anders suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.