Skip to content

Instantly share code, notes, and snippets.

@gudezhi
Last active November 23, 2023 13:53
Show Gist options
  • Save gudezhi/5687a373aded75dc8978ee797f91e0f7 to your computer and use it in GitHub Desktop.
Save gudezhi/5687a373aded75dc8978ee797f91e0f7 to your computer and use it in GitHub Desktop.
PostgreSQL相关

访问Docker下的PostgreSQL

  1. Identify the Container: First, identify the name or ID of your PostgreSQL Docker container. You can list all running containers using:

    docker ps
  2. Connect to the PostgreSQL Database: Use the docker exec command to start a bash shell inside the container, and then use the psql command-line tool to connect to your PostgreSQL database. For example:

    docker exec -it <container_name_or_id> bash

    Once inside the container, connect to the PostgreSQL database with:

    psql -U <username> -d <database_name>

    Replace <username> with your PostgreSQL username and <database_name> with the name of the database you want to connect to.

  3. Execute the SQL Command: After successfully connecting to the database, you can execute your SQL command. For instance:

    DROP TABLE IF EXISTS table_name;

    Replace table_name with the name of the table you want to drop.

  4. Exit psql and the Container: Once you have executed your SQL command, you can exit the psql prompt by typing \q and pressing Enter. Then, exit the Docker container shell by typing exit and pressing Enter.

Example: Here's an example of how these commands might look:

# List Docker containers to find the container name or ID
docker ps

# Start a bash shell in the PostgreSQL container
docker exec -it my_postgres_container bash

# Inside the container, connect to the PostgreSQL database
psql -U myusername -d mydatabase

# Inside the psql prompt, execute the DROP TABLE command
DROP TABLE IF EXISTS mytable;

# Exit the psql prompt
\q

# Exit the container's shell
exit

PostgreSQL 常用命令

# Inside psql, list all tables
\dt

# Or, for more details:
\dt+

# show columns of a table
\d+ <table_name> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment