Extract data from postgres using bulk loading - sql

CMD.EXE /C BCP "SELECT * FROM ci.trn_td_cash" queryout D:\Sample\data\Load\CASH.COPY -c -t"|" -r"\n" -S xxx.xxx.xxx.xx -d finance -U user -P 1111 .
I want to extract data from postgresql using bulk loading BCP command.Can i use BCP for posgresql. I use the following command for bulk loading. But it is not connecting to database.
please help me with syntax.

COPY Command in PostgreSQL:
The COPY command allows high-speed bulk data transfer to or from the server. Copy-in and copy-out operations each switch the connection into a distinct sub-protocol, which lasts until the operation is completed.
COPY command is supported in PostgreSQL Protocol v3.0 (Postgresql 7.4 or newer).
For more info follow the below link:
https://www.postgresql.org/docs/current/static/sql-copy.html
https://www.postgresql.org/docs/current/static/protocol-flow.html#PROTOCOL-COPY
GENERAL SYNTAX:
COPY (<select-query-here>) TO <file-path>;
Here is one answer I found to your question of how to run it:
https://ieftimov.com/postgresql-copy
Try this One:
\copy (note the backslash) lets you copy to/from remote databases and does not require superuser privileges.
psql -h remotehost -d remote_mydb -U
myuser -c "\copy mytable (column1, column2) from '/path/to/local/file.csv' with delimiter as ','"

Related

Import dump file containing a database dump to dbeaver

I have a database dump in thisdb_2022.dump binary file that I'm trying to import to dbeaver, but I haven't found a way to import the database so I can see it.
I found the below in the dbeaver forum but when I try to follow the instructions and create a new connection I don't see any option I can select that will open this document.
https://dbeaver.io/forum/viewtopic.php?f=2&t=895
Edit: The database and version is PostgreSQL 12
. I'm not trying to
dump it to an existing db rather I want to create a new one with this
dump.
the dump command looks like this: pg_dump -h blah.amazonaws.com -Fc -v --dbname="blah2" -f "/tmp/dump/20220203.dump".
And it will be the same version PostgreSQL 12
The easiest way to not use DBeaver at all.
Do:
UPDATED with correct command.
--In psql
CREATE DATABASE new_db;
--Exit psql
--At command line
pg_restore -d new_db -h <the_host> -p <the_port> -U postgres /tmp/dump/20220203.dump
To work in Dbeaver directly see Backup/Restore.

Create and import pgsql database after pg_dump

I am new to postgres. I have exported a large, complex database with the following command in the terminal
pg_dump -U USERNAME DBNAME > dbexport.pgsql
Now that I have transferred this .pgsql file to a different computer, what is the right command to automatically create and restore the exact same database as was exported? Any suggestions would be appreciated
The way you dumped the database, the information about the database itself is not included in the dump (which is a plain SQL file).
You can either use the -C option to include CREATE DATABASE in the dump (the dump has to be restored with psql), or you use the custom format:
pg_dump -F c -U postgres DBNAME -f dbexport.pgsql
That can be restored with pg_restore like this:
pg_restore -C -d postgres -U postgres dbexport.pgsql

How to execute postgres' sql queries from batch file?

I need to execute SQL from batch file.
I am executing following to connect to Postgres and select data from table
C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
select * from test;
I am able to connect to database, however I'm getting the error
'select' is not recognized as an internal or external command,
operable program or batch file.
Has anyone faced such issue?
This is one of the query i am trying, something similar works in shell script, (please ignore syntax error in the query if there are any)
copy testdata (col1,col2,col3) from '%filepath%/%csv_file%' with csv;
You could pipe it into psql
(
echo select * from test;
) | C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
When closing parenthesis are part of the SQL query they have to be escaped with three carets.
(
echo insert into testconfig(testid,scenarioid,testname ^^^) values( 1,1,'asdf'^^^);
) | psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
Use the -f parameter to pass the batch file name
C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME% -f 'sql_batch_file.sql'
http://www.postgresql.org/docs/current/static/app-psql.html
-f filename
--file=filename
Use the file filename as the source of commands instead of reading commands interactively. After the file is processed, psql terminates. This is in many ways equivalent to the meta-command \i.
If filename is - (hyphen), then standard input is read until an EOF indication or \q meta-command. Note however that Readline is not used in this case (much as if -n had been specified).
if running on Linux, this is what worked for me (need to update values below with your user, db name etc)
psql "host=YOUR_HOST port=YOUR_PORT dbname=YOUR_DB_NAME user=YOUR_USER_NAME password=YOUR_PASSWORD" -f "fully_qualified_path_to_your_script.sql"
You cannot put the query on separate line, batch interpreter will assume it's another command instead of a query for psql. I believe you will need to quote it as well.
I agree with Spidey:
1] if you are passing the file with the sql use -f or --file parameter
When you want to execute several commands the best way to do that is to add parameter -f, and after that just type path to your file without any " or ' marks (relative paths works also):
psql -h %host% -p 5432 -U %user% -d %dbname% -f ..\..\folder\Data.txt
It also works in .NET Core. I need it to add basic data to my database after migrations.
Kindly refer to the documentation
1] if you are passing the file with the sql use -f or --file parameter
2] if you are passing individual command use -c or --command parameter
If you are trying the shell script
psql postgresql://$username:$password#$host/$database < /app/sql_script/script.sql

Cannot execute script: Insufficient memory to continue the execution of the program

I have a 123MB sql file which I need to execute in my local PC. But I am getting
Cannot execute script: Insufficient memory to continue the execution of the program
How to solve this issue?
use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:
SQLCMD -d <database-name> -i filename.sql
You need valid credentials to access your SQL Server instance or even to access a database
Taken from here.
It might help you! Please see below steps.
sqlcmd -S server-name -d database-name -i script.sql
Open cmd.exe as Administrator.
Create Documents directory.
Put your SQL Script file(script.sql) in the documents folder.
Type query with sqlcmd, server-name, database-name and script-file-name as like above highlighted query or below command line screen.
For Windows Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
Note: If there is any space in the sql file path then use " (Quotation marks) "
For SQL Server Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -U sa -P sasa -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
-S TestSQLServer\SQLEXPRESS: Here specify SQL Server Name
-U sa: Username (in case of SQL Server Authentication)
-P sasa: Password (in case of SQL Server Authentication)
-d AdventureWorks2018: Database Name come here
-i "d:\document\sql document\script.sql": File Path of SQLFile
You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.
I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.
(This is the same answer I provided here)
My database was larger than 500mb, I then used the following
C:\Windows>sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -d DATABASE -i C:\FILE.sql
It loaded everything including SP's
*NB: Run the cmd as Administrator
If I understand your problem correctly, you are trying to restore (transact sql) xyz.sql - database + schema. You can try this command which worked for me:
SQLCMD -U sa -i xyz.sql
Try this step,
1)Open PowerShell
2)Write this command:
sqlcmd -S PCNAME\SQLEXPRESS -U user -P password -d databanse_name -i C:\script.sql
3)Press Return
:-)
Below script works perfectly:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Symptoms:
When executing a recovery script with sqlcmd utility, the ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered.
Cause:
This is a sqlcmd utility limitation. If the SQL script contains dollar sign ($) in any form, the utility is unable to properly execute the script, since it is substituting all variables automatically by default.
Resolution:
In order to execute script that has a dollar ($) sign in any form, it is necessary to add “-x” parameter to the command line.
e.g.
Original:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql
Fixed:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.
You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.
Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.
sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql
Open command prompt in run as administrator
enter above command
"mamxxxxxmu" is computer name
"sqlserverr" is server name
"sa" is username of server
"x1123" is password of server
"QLDB" is database name
"D:\qldbscript.sql" is sql script file to execute in database
If you need to connect to LocalDB during development, you can use:
sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql
As in most answers given here use the command-line tool. In my case the script already has database creation code. If your script contains CREATE DATABASE command, for example
USE [master]
GO
CREATE DATABASE [your-database-name]
Then do not use the -d your-database-name, instead use the following command.
For Windows Authentication use the command
sqlcmd -S ServerName\InstanceName -i "script.sql" -x
For SQL Server Authentication use the command
sqlcmd -S ServerName\InstanceName -U usename -P password -i "script.sql" -x

How do you run a single query through mysql from the command line?

I'm looking to be able to run a single query on a remote server in a scripted task.
For example, intuitively, I would imagine it would go something like:
mysql -uroot -p -hslavedb.mydomain.com mydb_production "select * from users;"
mysql -u <user> -p -e 'select * from schema.table'
(Note the use of single quotes rather than double quotes, to avoid the shell expanding the * into filenames)
mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"
From the usage printout:
-e, --execute=name
Execute command and quit. (Disables --force and history file)
here's how you can do it with a cool shell trick:
mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.
use the -t flag to enable table-format output
If it's a query you run often, you can store it in a file. Then any time you want to run it:
mysql < thefile
(with all the login and database flags of course)
echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production
As by the time of the question containerization wasn't that popular, this is how you pass a single query to a dockerized database cluster with Ansible, following #RC.'s answer:
ansible <host | group > -m shell -a "docker exec -it <container_name | container_id> mysql -u<your_user> -p<your_pass> <your_database> -e 'SELECT COUNT(*) FROM my_table;'"
If not using Ansible, just login to the server and use docker exec -it ... part.
MySQL will issue a warning that passing credentials in plain text may be insecure, so be aware of your risks.
From the mysql man page:
You can execute SQL statements in a script file (batch file) like this:
shell> mysql db_name < script.sql > output.tab
Put the query in script.sql and run it.