Skip to content

Instantly share code, notes, and snippets.

@akhilesh-sirvi92
Forked from ankurk91/import-sql.md
Created August 10, 2023 09:11
Show Gist options
  • Save akhilesh-sirvi92/7b1fd6b2ca8f978cddb920abe344847f to your computer and use it in GitHub Desktop.
Save akhilesh-sirvi92/7b1fd6b2ca8f978cddb920abe344847f to your computer and use it in GitHub Desktop.
MySQL/Postgresql: Import database via command line

Import large database to MySql ⚡

cd /path/to/backups
mysql -u root -h 127.0.0.1 -p --default-character-set=utf8
# Switch to database 
USE database_name;
SET names 'utf8';
SET autocommit=0;
SOURCE backup.sql;
COMMIT;
  • Note: database_name should exists
  • Source

Import/Export all databases in one command

Export

mysqldump -u root -h 127.0.0.1 -p --all-databases > all_db.sql

Import

mysql -u root -h 127.0.0.1 -p < all_db.sql

Import/Export single database

mysqldump --set-gtid-purged=OFF --no-tablespaces -h 127.0.0.1 -u root -p database_name_here > backup_file.sql
mysql -h 127.0.0.1 -u root -p database_name_here < backup_file.sql

Import export postgresql database running inside docker

Export

# get the container id
docker container ls

# Specify the container id in next command, for example 95bf1f75af9c
docker exec 95bf1f75af9c pg_dump -U postgres database_name > backup.sql

Import

docker exec -i 95bf1f75af9c psql -U postgres database_name < /full/path/to/backup.sql

Extras

Import database dump into PostgreSQL AWS RDS

Assumptions

  • You have postgres installed on your local machine
  • You have a database dump *.sql file created with psql command
  • You can SSH to EC2 instance
  • You have an EC2 instance running and EC2 machine has access to RDS instance

Steps

# Syntax
ssh -L <local free port>:<RDS instance host>:<RDS port> <ec2-user>@<ec2-ip-address>

# Example command
ssh -L 5433:db-name.c13mzxjj9hpa.us-east-1.rds.amazonaws.com:5432 [email protected]
  • Import the database to RDS (in new terminal window)
psql -U postgres -p 5433 -h 127.0.0.1 -d db_name < ./path/to/db_backup_file.sql
  • Close both terminal window when done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment