import .sql file in postgres using \i command from java - java

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

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,

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

Related

How to run mongo db script on remote server?

how to run a Mongo db script on a remote server?
I know below command can be used for the same on local as mentioned here:How to execute mongo commands through shell scripts?
mongo < yourFile.js
I want to run this script on a remote server
mongodb:uri:mongodb://user:password#mongodb01d.mydomain.com:27017/mydb
With Mongo on local machine :
mongo -u <user> -p <password> mongodb01d.mydomain.com:27017/mydb <yourFile.js>
It might be a little bit off topic, but in case you want to / have to use Powershell for a lack of options, you can run:
(Get-Content yourFile.js) | & mongo.exe 'mongodb://user:password#mongodb01d.mydomain.com:27017/mydb'
or
"print('Hello');print('Hello')" | & mongo.exe 'mongodb://user:password#mongodb01d.mydomain.com:27017/mydb'
or
& 'mongo.exe' 'mongodb://user:password#mongodb01d.mydomain.com:27017/mydb' --eval "print('Hello');print('Hello')"
I had some difficulties with $regex, because Powershell interpreted it as a variable, so I had to use `$regex (with an additional backtick) instead.

H2: generate insert scripts initialization script

I have full h2 database with lots data in it. I want to launch integration tests agains that data.
Question1: Is it possible to generate *.sql insert files/scripts from full h2 database?
I've trie SCRIPT TO 'fileName' as described here. But it generates only CREATE/ALTER TABLE/CONSTRAINT queries, means creating schema without data.
If answer to the first question is - "Impossible", than:
Question2: Are *.sql insert files the only way to insert initial dataset into h2 db for integration tests?
Question1: Is it possible to generate *.sql insert files/scripts from
full h2 database?
I have just tested with one of my H2 file databases and as result the export exports both structure and data.
I tested with the 1.4.193version of H2.
The both ways of exporting work :
The SCRIPT command from H2 console
org.h2.tools.Script tool from command line.
1) I have tested first the org.h2.tools.Script tool as I had already used it.
Here is the minimal command to export structure and data :
java -cp <whereFoundYourH2Jar> org.h2.tools.Script -url <url>
-user <user> -password <password>
Where :
<whereFoundYourH2Jar> is the classpath where you have the h2.jar lib (I used that one which is my m2 repo).
<url> is the url of your database
<user> is the user of the database
<password> the password of the database
You have more details in the official help of the org.h2.tools.Script tool :
Creates a SQL script file by extracting the schema and data of a database.
Usage: java org.h2.tools.Script <options>
Options are case sensitive. Supported options are:
[-help] or [-?] Print the list of options
[-url "<url>"] The database URL (jdbc:...)
[-user <user>] The user name (default: sa)
[-password <pwd>] The password
[-script <file>] The target script file name (default: backup.sql)
[-options ...] A list of options (only for embedded H2, see SCRIPT)
[-quiet] Do not print progress information
See also http://h2database.com/javadoc/org/h2/tools/Script.html
2) I have tested with SCRIPT command from the H2 console. It also works.
Nevertheless, the result of the SCRIPT command may be misleading.
Look at the official documentation :
If no 'TO fileName' clause is specified, the script is returned as a
result set. This command can be used to create a backup of the
database. For long term storage, it is more portable than copying the
database files.
If a 'TO fileName' clause is specified, then the whole script
(including insert statements) is written to this file, and a result
set without the insert statements is returned.
You have used the SCRIPT TO 'fileName' command. In this case, the whole script
(including insert statements) is written to this file and as result in the H2 console, you have everything but the insert statements.
For example, enter the SCRIPT TO 'D:\yourBackup.sql' command (or a Unix friendly directory if you use it), then open the file, you will see that SQL insertions are present.
As specified in the documentation, if you want to get both structure and insert statements in the output result of the H2 console, don't specify the TO argument.
Just type : SCRIPT.
Question2: Are *.sql insert files the only way to insert initial
dataset into h2 db for integration tests?
As a long time discussed :) you can with DBunit dataset (a solution among others).

No suitable driver when trying to create SQL database [duplicate]

This question already has answers here:
SQLException: No suitable driver found for jdbc:derby://localhost:1527
(19 answers)
Closed 7 years ago.
I am trying to create a new SQL database with this Java program
import java.sql.*; //Needed for JDBC classes
public class BuildPhonebookDB {
public static void main(String[] args) throws Exception{
//Create a named constant for the URL
final String DB_URL = "jdbc:derby:Phonebook;create=true";
try {
//Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
//Create a Statement object.
Statement stmt = conn.createStatement();
//Create the Entries table
stmt.execute("CREATE TABLE Entries (" +
"Name CHAR(20)"+
"Number INTEGER)"
);
System.out.println("Database Connected");
//Close the connection
conn.close();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When I try to run the program I get an error that:
No suitable driver found for jdbc:derby:Phonebook;create=true
I have looked at various other similar posts on Stack Overflow, such as this one, but none help. I have seen things about a driver jar, but I don't know what this is, if I need to edit this, could someone help me through it?
Thanks for any help
Did you see this guide and have you complited all step of this guide?
Apache Derby
Download Derby Download the binary Apache Derby distribution from the
Derby web site at http://db.apache.org/derby/derby_downloads.html.
These tutorial instructions use version 10.12.1.1 and assume you
downloaded one of the binary distribution files listed in the table
below:
Operating System Download File Windows db-derby-10.12.1.1-bin.zip
UNIX, Linux, and Mac db-derby-10.12.1.1-bin.tar.gz If a more recent
release is available, download that, then substitute that version
number for 10.12.1.1 in the following instructions.
Install Derby Choose the directory into which you want to install the
Derby software. You must have write permissions to this directory. The
sample instructions below use C:\Apache for Windows and /opt/Apache
for UNIX; be sure to use your actual location. Copy the software
distribution to the location you choose, then extract it as shown
below.
Windows (use your extraction tool e.g. WinZip -- these instructions
use mks unzip):
mkdir C:\Apache copy db-derby-10.12.1.1-bin.zip
> C:\Apache cd C:\Apache unzip db-derby-10.12.1.1-bin.zip
UNIX:
mkdir /opt/Apache cp db-derby-10.12.1.1-bin.tar.gz /opt/Apache
> cd /opt/Apache tar xzvf db-derby-10.12.1.1-bin.tar.gz
In both cases, the software will now be extracted into a subdirectory
named db-derby-10.12.1.1-bin.
Set DERBY_INSTALL Set the DERBY_INSTALL variable to the location where
you installed Derby. Examples are shown below, but be sure to use the
actual location on your system:
Windows: C:\> set DERBY_INSTALL=C:\Apache\db-derby-10.12.1.1-bin
UNIX Korn Shell:
$ export
> DERBY_INSTALL=/opt/Apache/db-derby-10.12.1.1-bin
Configure Embedded Derby To use Derby in its embedded mode set your
CLASSPATH to include the jar files listed below:
derby.jar: contains the Derby engine and the Derby Embedded JDBC
driver derbytools.jar: optional, provides the ij tool that is used by
a couple of sections in this tutorial You can set your CLASSPATH
explicitly with the command shown below:
Windows:
C:\> set
> CLASSPATH=%DERBY_INSTALL%\lib\derby.jar;%DERBY_INSTALL%\lib\derbytools.jar
;.
UNIX:
$ export
> CLASSPATH=$DERBY_INSTALL/lib/derby.jar:$DERBY_INSTALL/lib/derbytools.jar:.
...
Step 3: Embedded Derby
When an application accesses a Derby database using the Embedded Derby
JDBC driver, the Derby engine does not run in a separate process, and
there are no separate database processes to start up and shut down.
Instead, the Derby database engine runs inside the same Java Virtual
Machine (JVM) as the application. So, Derby becomes part of the
application just like any other jar file that the application uses.
Figure 1 depicts this embedded architecture.
Set the environment
To set up the environment, follow the "Configure Embedded Derby"
instructions.
Use this before you get the connection from the driver:
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();

How to run a Sqoop Import from a Hive Thrift Client to a Hive Thrift Server?

Using JDBC I easily connected and able to Run Hive-QL query with the following sample code:-
Connection con = DriverManager.getConnection("jdbc:hive2://192.168.56.102:10000/default", "", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable1";
stmt.executeQuery("create table " + tableName + " (key int, value string)");
This means I am able to communicate with Hive. Now I want to execute sqoop also. How can I do it? I did it through command line, see following sample import which worked
sqoop import --connect jdbc:mysql://192.168.56.101:3316/dw_db --username=user --password=pwd --table active_list --hive-import -m 1 -- --schema default
how this can be achive. And to make sure is that server running at 10000 port is Hive thrift Server? If yes so how can I make it to execute my sqoop query over Hive?

how to mysqldump on java?

I made my database in mySQL and I exported it in a file using mysqldump.
Is there a way to make my program on JAVA to connect in mysql and create an empty database with the stracture I saved in the file, only if the above database is not allready exist to the server?
Thank you!
Try something like :
Runtime.getRuntime().exec("mysql -u <username> -p<password> <youdbname> < <youbackupfile>");
you will need to replace <username> with your username / <password> with your password / <yourdbname> with you database name / <yourbackupfile> with the file you used for backup
FAQ for MySQL Backup

Categories

Resources