search
HomeDatabaseMysql TutorialPostgreSQL数据库(入门)

PostgreSQL数据库(入门)

Jun 07, 2016 pm 03:11 PM
postgresqlgetting StartedInstallplatformdatabase

安装 各个平台都有丰富的安装手册,详细可以在google里面搜索。这里是debian上安装方式,ubuntu类: aptitude install postgresql # 这个是数据库aptitude install pgadmin3 # 这个是GUI界面的管理工具 这里debian机器(172.16.70.175)是我笔记本,我是需要

安装

各个平台都有丰富的安装手册,详细可以在google里面搜索。这里是debian上安装方式,ubuntu类似:

<span>aptitude install postgresql  # 这个是数据库
aptitude install pgadmin3   # 这个是GUI界面的管理工具
</span>

这里debian机器(172.16.70.175)是我笔记本,我是需要一个pgadmin3,然后在实验机器(fedora系统,172.16.70.254)上安装了postgresql。

<span># rpm -qa|grep postgresql
postgresql-libs-8.3.7-1.fc10.i386
postgresql-8.3.7-1.fc10.i386
postgresql-server-8.3.7-1.fc10.i386
</span>

初始化配置

postgresql的用户和系统用户是分开的,我们需要初始化数据库,设置数据库的Loading用户,配置postgresql的访问权限。

设置密码

如果是在debian/ubuntu,或者fedora这些系统上使用deb或rpm包安装的,都会建立好postgres用户。我们需要以这个用户权限运行psql命令设置postgres用户密码:

<span># su postgres -c psql template1
欢迎来到 psql 8.3.7,这是 PostgreSQL 互动式文字终端机。

键入: \copyright 显示发行条款
       \h 显示 SQL 命令的说明
       \? 显示 pgsql 命令的说明
       \g 或者以分号(;)结尾以执行查询
       \q 退出

postgres=# ALTER USER postgres with password 'abc123';
ALTER ROLE
postgres=# \q
</span>

上面abc123就是我们设置的密码。

创建数据库

<span>su postgres -c createdb mydb
</span>

配置远程链接

1. 首先看看防火墙是否开启,如果开启需要允许5432端口的联通。如不知怎样配置防火墙,就关闭它。

2. 配置postgresql.conf文件,这个文件在数据库pgsql目录下的data目录里。我在fedora上现在的地方是/var/lib/pgsql/data/postgresql.conf。

<span>listen_addresses = '*'   #把这句的注释去掉,'*' 号表示监听所有网络地址的链接
</span>

3. 配置pg_hba.conf文件,通常和postgresql.conf文件在同一个目录下:

<span>host    all         all         172.16.70.175   255.255.252.0   md5
# 我在最后加上了这一句
# 我的笔记本IP是175, netmask是255.255.252.0
# 这里和我同一网段的机器都以链接
</span>

4. 重启postgresql服务

<span># /etc/init.d/postgresql restart
停止 postgresql 服务:                                     [确定]
启动 postgresql 服务:                                     [确定]
</span>

用户管理

创建用户 createuser

<span>createuser 是 SQL 命令 CREATE USER的封装。
命令:createuser [-a] [-A] [-d] [-D] [-e] [-P] [-h 主机名] [-p port] 用户名
参数说明:
[-a]:允许创建其他其他用户;
[-d]:允许此用户创建数据用户,相当于创建一个超级用户;
[-A]:不允许此用户创建库库;
[-e]:将执行过程显示到Shell上;
[-P]:创建用户时,同时设置密;
[-D]:不允许此用户创建数据码;
[-h 主机名]:为某个主机上的Postgres创建用户;
[-p port]:与-h参数一同使用,指定主机的端口。
</span>

1. 直接运行createruser命令

<span># createuser
Enter name of role to add: jianlee
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y
createuser: 无法联接到数据库 postgres: 致命错误:  用户 "root" Ident 认证失败
</span>

上面命令运行出错的原因是root用户没有权限访问数据库,我们使用前面设置密码的postgres用户运行命令:

<span># su postgres
bash-3.2$ createuser
Enter name of role to add: jianlee
Shall the new role be a superuser? (y/n) n  # 如果选择y,那么jianlee就是超级用户
Shall the new role be allowed to create databases? (y/n) y #如果上面没有选择y,这里才出现
Shall the new role be allowed to create more new roles? (y/n) y #同上
</span>

2. 为指定的主机和端口创建用户(就是远程创建用户)

<span># su postgres
postgres@jianlee:/root$ createuser -h 172.16.70.254 -p 5432 -D -A -e turbolinux
Shall the new role be allowed to create more new roles? (y/n) y
口令:     # 输入用户postgres的口令
CREATE ROLE turbolinux NOSUPERUSER NOCREATEDB CREATEROLE INHERIT LOGIN;
</span>

这个例子我在debian机器上先su到postgres用户下执行createuser命令,-h和-p指定远程主机的ip和端口,turbolinux是我想创建的用户名。必须远程(172.16.70.254)机器上的postgresql服务器启动并且postgres用户可以从debian(172.16.70.175)访问情况下,才能执行正确。

3. 创建超级用户

<span>$ createuser -P -d -a -e turbo_rd
Enter password for new role:
再输入一遍:
CREATE ROLE turbo_rd PASSWORD 'md5259766bbac3b83cd9195cc0bea6ecec7' \
SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;
</span>

参数看本节开始的createuser参数说明。

删除用户 dropuser

<span>$ dropuser --help
dropuser removes a PostgreSQL role.

使用方法:
  dropuser [OPTION]... [ROLENAME]

选项:
  -e, --echo                显示发送到服务端的命令
  -i, --interactive         删除任何东西之前给予提示
  -h, --host=HOSTNAM        数据库服务器所在机器的主机名或套接字目录
  -p, --port=PORT           数据库服务器端口号
  -U, --username=USERNAME   联接用户 (不是要删除的用户名)
  -W, --password            force password prompt
  --help                    显示此帮助信息, 然后退出
  --version                 输出版本信息, 然后退出

臭虫报告至 <pgsql-bugs>.
</pgsql-bugs></span>

1. 本地删除

<span>$ dropuser -i -e turbo_rd
Role "turbo_rd" will be permanently removed.
你确定吗? (y/n) y
DROP ROLE turbo_rd;
</span>

2. 远程删除

<span>$ dropuser -p 5432 -h 172.16.70.254 -i -e turbolinux
Role "turbolinux" will be permanently removed.
你确定吗? (y/n) y
口令:
DROP ROLE turbolinux;</span>

再次提醒:本次命令的运行者必须是能登录254机器上数据库的用户。'口令'也是该用户的数据库登录口令。

数据库简单管理

创建数据库 createdb

<span>createdb 中文
</span>

注意,运行这个命令的用户需要是postgresql服务器用户,有建库权限。

删除数据库 dropdb

访问数据库

1. 使用psql命令行

$ psql 中文
欢迎来到 psql 8.3.7,这是 PostgreSQL 互动式文字终端机。

键入: \copyright 显示发行条款
       \h 显示 SQL 命令的说明
       \? 显示 pgsql 命令的说明
       \g 或者以分号(;)结尾以执行查询
       \q 退出

中文=#

2. 使用pgadmin3图形界面管理工具

表操作

创建完数据库之后,我们就可以在数据库里面创建表了。我用的postgresql版本是8.3(debian lenny),表名、表中的所有字段的名字和注释可以是UTF-8字符。但是用英文名字可以TAB键补全的地方多,不过这里我还是用中文表示。例子是参考postgresql的wiki上的。

创建新表

首先启动psql命令行程序,然后创建新表:

<span>root@jianlee:~# psql -U postgres -h localhost
欢迎来到 psql 8.3.6,这是 PostgreSQL 互动式文字终端机。
...
postgres=# CREATE TABLE 天气(
城市 varchar(80),  -- 这是城市名字
最低气温 int, -- 一天当中最低气温
最高气温 int, -- 一天当中最高气温
降水量  real, -- 当天的降水量
日期    date -- 日期
);
CREATE TABLE   </span>

注意 : 最后一行date字符后面没有 ',' 号!如果加上逗号会出现语法错误。

除了常用的 \q \? 等命令,psql里面的一条命令是以 ';' 结束的。在SQL里面可以随意使用空白(空格、tab、换行符)。 是注释的开始,到换行符结束。SQL对于大小写不敏感,之用在双引号字符串中才区分大小写。

常见错误

pgadmin3-"服务器工具未安装"

参考:http://techxplorer.com/2008/01/16/installing-postgresql-server-instrumentation-under-ubuntu/

1. 安装 postgresql-contrib 包

2. 运行命令:

psql -U postgres -d postgres -h localhost 
<br>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.