Skip to content

Instantly share code, notes, and snippets.

@ankurk91
Last active February 20, 2025 05:52
Show Gist options
  • Save ankurk91/e12f9f2cd5cceb4a5d76e2ebba2fbaa0 to your computer and use it in GitHub Desktop.
Save ankurk91/e12f9f2cd5cceb4a5d76e2ebba2fbaa0 to your computer and use it in GitHub Desktop.
MySQL/Postgresql/Mongo: 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

Export

mongodump --uri "mongodb+srv://db-user:[email protected]/db-name?retryWrites=true&w=majority" --out ~/mongo-db

Import

mongorestore --uri "mongodb+srv://db-user:[email protected]/?retryWrites=true&w=majority" ~/mongo-db

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 --column-statistics=0 --set-gtid-purged=OFF --no-tablespaces -v -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.
@ankurk91
Copy link
Author

@rajesh-ivd Please use stack overflow to ask your questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment