Now that I've become an engineer and have come into contact with Linux and PostgreSQL, I'll keep what I've learned as a record. The environment is CentOS 7.2. Use PostgreSQL.
Use the psql command to work with the DB. The psql command is a command for operating the DB from the terminal. However, not all users can use this command. (It seems possible if you change the setting.) When operating the DB, switch to the postgres user (or switch to a user who can use the psql command) instead of the root user or general user, and execute the psqk command to operate the DB. The su and sudo commands are used when switching between users.
The su command is substitute user, super user, switch user, etc. I looked it up, but I didn't know what it stands for. It means to switch users.
su - postgres
Switching to postgres user.
Regarding the presence or absence of hyphens
Note the presence or absence of "-". If there is a "-", the environment will be initialized as if you logged in directly. That is, the current directory will be the new user's home directory and all environment variables will be initialized. If there is no "-", the current environment is left as it is and only the user is switched. (Nakajima Nokazu "LinuC Textbook LinuC Level 1 Version 10.0 Compatible" p425)
It seems that.
su -
password:
If you omit the user name, you will be switched to the root user and asked for a password.
su - postgres
#Switch user to postgres
psql test
#Access the test server with the psql command
¥d
#You can list the tables in the test server by using the \ mark (or backslash) d.
¥d table
#You can also list the columns in that table by entering the table name after \ d.
After switching to the postgres user with the su command, specify the target server with the psql command, You will be writing SQL statements such as SELECT. If you switch users, it will remain the same, so you can return to the original user with ctrl + d.
In the case of the sudo command, you can write SQL statements in one line from sudo.
sudo -u postgres psql table -c "SELECT~";
Switch postgres user with u option from sudo command, specify DB called table from psql command, Since you type the command in succession, you can enter the SQL statement by enclosing it in c option and double quotation marks.
sudo -u postgres psql table -f /var/test.sql
Also, if the SQL statement is put together in a file, it can be executed by changing the c option to the f option. In the above case, the test.sql file under / var is being executed.
However, since the sudo command has to switch users each time and write SQL statements, It may be better to switch once with the su command when writing SQL statements many times.
Described the difference between su and sudo for switching to the postgres user. I think it's deeper, but I'll learn from now on.
Recommended Posts