Tuesday, December 15, 2020

MySQL and PostgreSQL command line cheat sheet

 MySQL

From https://www.a2hosting.in/kb/developer-corner/mysql/managing-mysql-databases-and-users-from-the-command-line

mysql -u root -p
(or bitnami user for bitnami VMs)

show databases;
use dbname1; 
show tables; 

create database dbname;
use dbname;
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';

Example SQL script import usage

mysql -u username -p < example.sql

And if required,

drop table tablename;

or

drop database dbname;

For cloning a database, this page has instructions, which also needed the permissions as detailed here. as root user, opening mysql and
GRANT PROCESS, SELECT, LOCK TABLES ON *.* TO 'bn_alfresco'@'localhost'; 

mysqldump -u bn_alfresco -p bitnami_alfresco -r bnalf.sql

mysql -u bn_alfresco -p

CREATE DATABASE my_project_copy;
USE my_project_copy;
SOURCE bnalf.sql;

PostgreSQL

For Debian-based distributions, 
sudo apt-get install postgresql-client
psql -h <REMOTE HOST> -p <REMOTE PORT> -U <DB_USER> <DB_NAME>

\l

to show databases, or

select datname from pg_database;

And to show tables,

\c databasename
\dt

Edit: For exporting the database, various options for pg_dump, most common would be
sudo su postgres
pg_dump dbname > dumpfile.sql

or if local authentication is not supported in the hba.conf, and username/pw auth is supported,
pg_dump --no-owner --dbname=postgresql://dbuser:dbuserpasswd@host:port/dbname > dump.sql

From bash shell, as postgres user, can import like
psql dbname < dbdump.sql

From https://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e

create database dbname;
create user username;
(To change, alter user username with encrypted password 'MyPassWord';)
grant all privileges on database dbname to username;

If the database was imported as postgres user, and another user is given all privileges as above, a possible issue is "permission denied when accessing schema postgres". My rough workaround was to create another super user (since I did not know the postgres user's password and didn't want to change it and potentially break things) by logging on as root, su postgres, and 
CREATE USER newadmin WITH SUPERUSER PASSWORD 'newadminpassword';

No comments:

Post a Comment