📜  PostgreSQL创建数据库

📅  最后修改于: 2020-11-30 01:03:43             🧑  作者: Mango

PostgreSQL创建数据库

在本节中,我们将讨论如何在PostgreSQL中创建数据库。

PostgreSQL中,我们可以通过两种方式创建数据库:

  • PostgreSQL使用pgAdmin创建数据库
  • PSQL创建数据库命令行(SQL Shell)

使用pgAdmin创建数据库

要在pgAdmin中创建数据库,我们将遵循以下步骤:

步骤1

  • 首先,我们将在本地系统中打开pgAdmin,然后在“对象”树中,右键单击“数据库”并选择“创建”,然后选择“数据库”

数据库→创建→数据库

第2步

  • 之后,将打开“创建数据库”窗口,我们需要在其中提供一些必要的详细信息(数据库名称,注释)以创建数据库,然后单击“保存”。

第三步

  • 如下面的屏幕快照所示,数据库已创建并显示在对象树中:

第四步

  • 右侧窗口将为我们提供用于创建数据库的SQL,如下图所示:

创建数据库的语法

在PostgreSQL中创建数据库的完整语法如下:

CREATE DATABASE db_name
OWNER =  role_name
TEMPLATE = template            
ENCODING = encoding            
LC_COLLATE = collate            
LC_CTYPE = ctype
TABLESPACE = tablespace_name
CONNECTION LIMIT = max_concurrent_connection

在以上语法中,我们具有以下参数:

Parameters Description
db_name We will use this parameter to specify the new database name, which we want to create. And we also ensure that the database must be unique because If we try to create a new database with the same name as an existing database, it will show an error.
role_name It is used to describe the role name for the user who will have the new database, and by default, it is postgres.
Template While creating the new database, we will require database template name.
Encoding It is used to describe the character set encoding for the new database, and by default, it is UTF8.
Collate It is used to define the sort order of strings that mark the result of the ORDER BY clause if we are using a SELECT statement.
Ctype This parameter is used to display the character classification for the new database.
tablespace_name It is used to define the tablespace name for the new database, and by default, it is the template database’s tablespace.
max_concurrent_connection This parameter is used to define the maximum parallel connections of a new database, and by default, it is -1 (unlimited).

失误

使用create database命令时,我们可能会遇到以下错误:

  • 服务器中没有这样的文件正在本地执行并接受Unix域套接字上的连接:如果使用create database命令并且服务器未启动,则会收到错误。
  • 没有授予创建数据库的权限:当我们需要授权相关用户使用create命令时,将发生此错误。并且已创建PostgreSQL帐户,但无权创建数据库。
  • 找不到“创建数据库”命令:如果PostgreSQL安装不正确,则可能会遇到这种类型的错误,因此需要从PostgreSQL安装路径执行“创建数据库”命令。

创建数据库命令行(SQL Shell)

要在命令行中创建数据库,我们将遵循以下步骤:

步骤1

  • 首先,我们将在本地系统中打开SQL Shell。为此,我们将转到主页按钮并搜索pSQL并将其打开。

第2步

  • 打开SQL Shell之后,我们将按Enter键4-5次,然后为用户(我们之前创建的)提供密码以连接数据库,如下面的屏幕快照所示:

第三步

之后,输入以下命令创建数据库

CREATE DATABASE Javatpoint;

第四步

要获取先前创建的所有数据库的列表,我们将输入以下命令:

\l

第5步

要连接到数据库,我们将输入以下命令:

\c javatpoint

  • 正如我们在上面的屏幕截图中看到的那样,我们通过命令提示符连接到数据库Javatpoint。
  • 我们还可以执行各种命令,例如Trigger,Create Table等。