新手求助:如何通过psql命令行创建数据库并插入数据
Hey there! Since you're new to PostgreSQL and psql, let's break down exactly how to create a database and insert data using only the psql command line—no extra tools required. I'll keep this straightforward and step-by-step.
First, open your terminal/command prompt and connect to the default PostgreSQL admin database (this is where you'll create your new database). Run this command:
psql -U postgres
- The
-Uflag specifies the username;postgresis the default superuser account created during installation. - You'll be prompted for the password you set during PostgreSQL setup (if you enabled password authentication).
Once you're inside the psql shell (you'll see a postgres=# prompt), run this SQL command to create your database. Replace my_first_db with whatever name you want:
CREATE DATABASE my_first_db;
- Don't forget the semicolon at the end—SQL commands in psql require this to execute!
- You'll see a message like
CREATE DATABASEif it worked.
Now you need to connect to the database you just created. Use this psql meta-command (note: no semicolon needed here):
\c my_first_db
Your prompt will change to my_first_db=#, confirming you're connected to the right database.
Before inserting data, you need a table to store it in. Let's create a simple example table for users. Run this SQL:
CREATE TABLE users ( id SERIAL PRIMARY KEY, -- Auto-incrementing unique ID name VARCHAR(50) NOT NULL, -- User's name (required) email VARCHAR(100) UNIQUE NOT NULL -- Unique email (required) );
You'll see CREATE TABLE once it's done.
Now you can insert rows of data. Here's how to do it one or multiple records at once:
Insert a single record:
INSERT INTO users (name, email) VALUES ('Jane Doe', 'jane@example.com');
Insert multiple records at once (more efficient):
INSERT INTO users (name, email) VALUES ('John Smith', 'john@example.com'), ('Sarah Lee', 'sarah@example.com');
After running either, you'll get a message like INSERT 0 2 (the number at the end is how many rows were added).
Verify the Data Was Inserted
To make sure your data is there, run a simple select query:
SELECT * FROM users;
You'll see a table with all the rows you inserted.
If you don't want to go into the psql shell first, you can create a database directly using the createdb system command:
createdb -U postgres my_first_db
Then you can connect to it later with psql -U postgres -d my_first_db.
- To exit the psql shell at any time, type
\qand press Enter. - If you forget a command, type
\hfor SQL help or\?for psql meta-command help.
内容的提问来源于stack exchange,提问作者dtb




