Linux command
psql 命令
文本
复制后可按需替换文件名、目录或参数。
常用示例
Connect to database
psql -d [database]
Connect to remote server
psql -h [host] -U [user] -d [database]
Execute SQL command
psql -c "SELECT * FROM [table]" [database]
Execute SQL file
psql -f [script.sql] [database]
List databases
psql -l
Interactive mode
psql [database]
说明
psql is the official interactive terminal for PostgreSQL. It provides a command-line interface for connecting to databases, executing SQL queries, and managing database objects. In interactive mode, it offers features like tab completion, command history, and formatted output for query results. Beyond interactive use, psql can execute SQL files with -f and run individual commands with -c, making it suitable for scripting and automation. Built-in backslash commands (like \dt for tables, \d for describing objects, and \l for listing databases) provide quick access to database metadata without writing SQL. Connection parameters can be specified via command-line flags, environment variables (PGHOST, PGUSER, PGDATABASE, PGPORT), or the ~/.pgpass file for password-free authentication.
参数
- -h _HOST_
- Server hostname.
- -p _PORT_
- Port number.
- -U _USER_
- Username.
- -d _DBNAME_
- Database name.
- -c _COMMAND_
- Execute command.
- -f _FILE_
- Execute file.
- -l
- List databases.
FAQ
What is the psql command used for?
psql is the official interactive terminal for PostgreSQL. It provides a command-line interface for connecting to databases, executing SQL queries, and managing database objects. In interactive mode, it offers features like tab completion, command history, and formatted output for query results. Beyond interactive use, psql can execute SQL files with -f and run individual commands with -c, making it suitable for scripting and automation. Built-in backslash commands (like \dt for tables, \d for describing objects, and \l for listing databases) provide quick access to database metadata without writing SQL. Connection parameters can be specified via command-line flags, environment variables (PGHOST, PGUSER, PGDATABASE, PGPORT), or the ~/.pgpass file for password-free authentication.
How do I run a basic psql example?
Run `psql -d [database]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does -h _HOST_ do in psql?
Server hostname.