PostgreSQL database servers to install and simple to use

Author: Small P
from: LinuxSir.Org
Summary: PostgreSQL is now one of the more popular databases, which originated in the Berkeley (BSD) database research program is now derived to an international development projects, and has a very wide range of users. I understand that the four largest domestic databases, three of which are based on PostgreSQL development. And because flexible licenses, anyone is free to use for any purpose, modify and distribute PostgreSQL, whether private, commercial, academic or research use. This article is a brief introduction to install and simple to use postgresql, the grammar involved is relatively small, in order to facilitate the Novice for the purpose.
table of Contents


1. System environment and installation method; 1.1 system environment; 1.2 installation; 2. Start PostgreSQL database server; 2.1 startup method popular Linux distributions; 2.2 on PostgreSQL start and storage directory; 3. Create a user; 3.1 Add user; 3.1 .1 create a user with no parameters; 3.1.2 Creating users on the specified host and port; 3.1.3 to create a super-user; 3.2 delete user: 3.2.1 delete the local Postgres users; 3.2.2 delete on the remote Postgres server users; 4. create and delete databases; 5. Access database 6. Postgresql graphical management tool pgAdmin3; 7. create and delete tables; 8. Add rows to the table; 9. query a table; 10. The view; 11. Update rows; 12. delete rows; 13. About herein; 14. Update log; 15. documented; 16 related documents;
++++++++++++++++ +++++++++++++++++++++++++++
text
++++++++++++++++++++++ +++++++++++++++++++++
PostgreSQL is one of the more popular database now, this originated in the Berkeley (BSD) database research program is now derived to an international development project and has a very wide range of users. I understand that the four largest domestic databases, three of which are based on PostgreSQL development. And because flexible licenses, anyone is free to use for any purpose, modify and distribute PostgreSQL, whether private, commercial, academic or research use. This article is a brief introduction to install and simple to use postgresql, the grammar involved is relatively small, in order to facilitate the Novice for the purpose.
1. System environment and installation method;
PostgreSQL installation method is more flexible, you can use the source code package is installed, you can also use software package release brought you use to install, can also use the online installation ......
1.1 System environment: Ubuntu Linux 7.04; Fedora; Slackware;

1.2 installed;
under Ubuntu is actually very simple to install software, use Synaptic package Manager will be able to search psql found postgresql-client-8.2 (at the same time can be found to version 8.1, which can be), select - applications can be. Or at the input terminal
xiaop@localhost$ sudo apt-get install postgresql-8.2
Slackware installation: Please go to find the corresponding version of the system you are using, with pkginstall to install, or you install slap-get tool linuxpackages.net, automatically downloaded and installed; use to root privileges, can be common sudo. Su and sudo on the reference; "control Linux system root authority" to install the postgresql package, available the following way;
xiaop@localhost# pkginstall post*.tgz

xiaop@localhost# slapt-get --install postgresql-8.2.4
In Fedora, you can use the online package installation tool to install Note: This installed the PostgreSQL 8.2, and the installation will automatically create a default database cluster (in translation pgsqldb.org) "main", and generate a database superuser postgres.
2. Start PostgreSQL database server;

2.1 startup method popular Linux distributions;
in the Ubuntu system, the server startup script in the /etc/init.d directory, you can use the following method to start, but also for Fedora and Gentoo akin;
xiaop@localhost~# /etc/init.d/postgresql-8.2 start  注:启动;
xiaop@localhost~# /etc/init.d/postgresql-8.2 restart  注:重启;
xiaop@localhost~# /etc/init.d/postgresql-8.2 stop 注:停止;
xiaop@localhost~# /etc/init.d/postgresql-8.2  status  注:查看状态;
In the Slackware, PostgreSQL startup script in /etc/rc.d directory, if you use the package downloaded from the linuxpackages.net installed software package or online;
xiaop@localhost~#  /etc/rc.d/rc.postgres start
If you compile with the source package installation, start PostgreSQL, please see PostgreSQL official documentation;
2.2 on PostgreSQL start and storage directory;
start PostgreSQL server, and is usually postgres user to start, with the exception of self-compiled and installed; for storing a database of general is placed in / var / lib relevant directories such as / var / lib / pgsql directory or /var/lib/postgresql/8.2/main/ such as; different distributions may not be the same, but still very much the same, you can modify data storage location to the database exists elsewhere;
3. Create a user

to add a user command format.
createuser package is the SQL command CREATE USER.
Command: createuser [-a] [-A] [-d] [-D] [-e] [-P] [-h hostname] [-p port] User Name
Parameters:
[-a]: allows to create other users, to create the equivalent of a super-user;
[-A]: this user is not allowed to create other users;
[-d]: allowed to create a database;
[-D]: this user is not allowed to create a database;
[-e] : the execution is displayed on the Shell;
[-P]: when creating a user, and password;
[-h hostname]: create a user for Postgres on a host;
[-p Port]: together with the -h parameter , specify the port of the host.
3.1 Adding users;

3.1.1 without creating a user parameter;
xiaop@localhost~$ createuser testuser
Shall the new user be allowed to create databases? (y/n) n    --------是否可以创建数据库:否
Shall the new user be allowed to create more new users? (y/n) n     ---------是否可以创建新用户:否
CREATE USER
Note: When you create a user with no parameters, Postgres will ask the user's permission, the above example to create a normal user;
3.1.2 Creating users on the specified host and port;
xiaop@localhost~$ createuser -h 172.28.18.51 -p 5000 -D -A -e testuser
CREATE USER joe NOCREATEDB NOCREATEUSER;
CREATE USER

NOTE: The host port 5000 to create the user testuser 172.28.18.51 this command, the user can not create databases and other users.
3.1.3 Create a super user;
xiaop@localhost~$ createuser -P -d -a -e testuser
Enter password for new user: testuser
Enter it again: testuser
CREATE USER joe PASSWORD 'testuser' CREATEDB CREATEUSER;
CREATE USER
Note: This command creates a local super-user (-a), you can create a database (-d), while requiring a password.
3.2 Delete user:
command: dropuser [-i] [-h] [-p] [-e] Username Parameters:
[-i]: Before deleting the user, asking for confirmation;
[-h hostname]: delete a Postgres user on the host;
[-p port]: -h parameters, are used, the port specified host;
[-e]: the execution is displayed on the Shell.
Postgres 3.2.1 delete the local user;
xiaop@localhost~$ dropuser testuser
DROP USER

3.2.2 To delete a user on the remote Postgres server;
xiaop@localhost~$ dropuser -p 5000 -h 172.28.18.51 -i -e testuser
User "testuser" and any owned databases will be permanently deleted.
Are you sure? (y/n) y
DROP USER "testuser"
DROP USER

Note: This command deletes a host 172.28.18.51 (-h) 5000 port (-p) of the user testuser, and the need to confirm (-i);
4. Create and delete databases;

4.1 to create a database
to see if you can access the database server the first example is to try to create a database;
to create a new database, called in our example mydb, you can use the following command:
xiaop@localhost~$ createdb mydb
It should generate a response such as the following:
CREATE DATABASE
If so, then this step is successful, if you see something like this information
createdb: command not found
So PostgreSQL is not installed, or it is not installed at all;
you can also create databases with other names. PostgreSQL allows you to create any number of databases on a single node. Database names must begin with a letter and be less than 63 characters long. The practice is to create a convenient and user name the same name as your current database. Many tools assume that database names are the default database name, so this can save you some typing. To create that database, simply type:
xiaop@localhost~$ createdb

4.2 delete the database

if you do not want to use your database, then you can delete it. For example, if you are mydb database owner (founder), then you can delete it with the following command:
xiaop@localhost~$ dropdb mydb
Note :( For this command, the database name is not the default user name. So you have to declare it.) This action will all associated with the physical database files are deleted and can not be canceled, so do it before must make it clear;
5. access database
Once you have created a database, you can access it, you can run the PostgreSQL interactive terminal program, called psql, which allows you to interactively enter, edit, and execute SQL commands. (Graphical login See 6. Postgresql graphical management tool pgAdmin3)
5.1 activate the database

you need an example psql, just start the test. You can activate it with the following command mydb database:
xiaop@localhost~$ psql mydb
If you omit the database name, then it is your default user account name.
Welcome to psql 8.2.4, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

mydb=#
Note: The last line mydb = #, this prompt means that you are a database superuser.
5.2 Help, and Exit database

psql program has a number of internal commands are not SQL commands. They start with a backslash, "\." Some of these commands are listed in the welcome message. For example, you can get help syntax of various PostgreSQL SQL commands with the following command:
mydb=> \h
To exit psql, type
mydb=> \q

Then psql will quit and return you to the command line shell; (For more information about the internal command, you can type in the psql prompt \ ?.)
6. Postgresql graphical management tool pgAdmin3;

version: Version1. 4.3
6.1 installation;

6.1.1 Ubuntu installation;

there are two ways: 1. Search pgadmin3 in Synaptic package Manager, find pgadmin3-- application terminal 2. enter the command:
       
xiaop@xiaop-laptop:~$ sudo apt-get install pgadmin3

6.1.2 Other installation systems;

You can refer to the normal software installation method other systems, since this is similar to, herein do not introduced;
the simple use of 6.2 pgAdmin3;

graphical management system is relatively intuitive, you can command under line operation, and then view the results in the next pgAdmin3;
6.2.1 pgAdmin3 start

you can find pgAdmin3 startup items in the application --- system tools;
can also be entered at the command line:
xiaop@xiaop-laptop:~$ /usr/bin/pgadmin3 start

6.2.2 mydb database connection has been created;
click on File ----- new server, and then jump out the window at the input:
地址:localhost
描述:服务器名称(随意填写)
维护数据库:postgres
用户名:自己创建一个(详情参见创建用户)
密码:和用户名对应(创建用户时自己创建)

Click OK after you will be able to view postsql the existing database;
Note: The database under pgAdmin3 database and create terminal is fully synchronized (can be refreshed to see the effect), pgAdmin3 is more convenient graphical management tool that can create graphics, database management and other details about pgAdmin3 we discuss later in this article focuses on operating under the command line. Graphical management tool can do command row can be done, you can create a table in the command line to see if sync on pgAdmin3: 7. create and delete tables;

7.1 to create a new table;

you have created a database after you You can create a new table, you can create a table by name and type the name of the table and declare all fields, such as:
mydb#CREATE TABLE weather (
                city            varchar(80),
                temp_lo         int,           -- 最低气温
                temp_hi         int,           -- 最高气温
                prcp            real,          -- 降水量
                date            date
                     );

Note: You can even type these line breaks things together in psql. psql can recognize the command until the semicolon until the end, do not forget the ";"
You are free to use the blank (ie space, tab, and newline) in the SQL command. This means that you can use and above use different ways to type commands. Two dash ( "-") introduce a comment. Any behind it with something until the end of the line are ignored. SQL keywords and identifiers is case-insensitive language, only if the identifier surrounded by double quotes in order to retain their case attributes.
7.2 Data type;

the example above varchar (80) may store a data type declaration up to 80 characters of arbitrary character string. int is the normal integer types. It is a type of real storage for single precision float. date type should be self-explanatory.
PostgresSQL supports standard SQL type int, smallint, real, double precision , char (N), varchar (N), date, time, timestamp , and interval, also support other types of common and abundant types of geometry. PostgreSQL can be customized to any client into a user-defined data type, you can refer to the PostgreSQL Chinese document to query;
7.3 Delete table;

if you no longer need a table, or if you want to create a different table, you can use the following command deletes it:
mydb#DROP TABLE tablename

8. Add a row to the table;

8.1 the INSERT;

the INSERT to add a row to the table, you can enter (the database operation):
mydb#INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');

Note: All data types are used fairly straightforward input format. Constants that are not required by single quotes simple digital value ( ') surrounded by, just like in the example.
8.2 point type input;

Point type requires a coordinate pair as input, as follows:
mydb#INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)');

8.3 COPY;

you can also use COPY to load large amounts of data from a text file. Do it usually faster because the COPY command is optimized for such applications, but less flexibility than INSERT. such as:
mydb#COPY weather FROM '/home/user/weather.txt';

Note: weather.txt is written in advance of your table of contents document conforms to a standard format;
9. query a table;

9.1 the SELECT;

from one table to retrieve data is to query the table. SQL's SELECT is doing this purpose. This statement is divided into the selection list (list fields section to return), the list table (the table lists the portion of data retrieved from), and optionally the conditions (of arbitrary restriction portion). For example, to retrieve all the rows in the table weather, type:
SELECT * FROM weather; 
<code>

输出结果:
<code>

     city      | temp_lo | temp_hi | prcp |    date   
---------------+---------+---------+------+------------
San Francisco |      46 |      50 | 0.25 | 1994-11-27
San Francisco |      43 |      57 |    0 | 1994-11-29
Hayward       |      37 |      54 |      | 1994-11-29
(3 rows)
You can write any expression in the select list, rather than just a list of fields. For example, you can:
SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;

This should come:
     city      | temp_avg |    date
---------------+----------+------------
San Francisco |       48 | 1994-11-27
San Francisco |       50 | 1994-11-29
Hayward       |       45 | 1994-11-29
(3 rows)

Note here how the AS clause to rename the output fields. (AS clause is optional.)
9.2 WHERE;

a query using the WHERE clause "modification", a statement which rows need. WHERE clause contains a Boolean (true value) expression, the Boolean expression is true only those rows are returned. It allows you to use usual Boolean operators (AND, OR, and NOT) in the condition. For example, the following query retrieves San Francisco rainy weather:
mydb#SELECT * FROM weather
    WHERE city = 'San Francisco' AND prcp > 0.0;

result:
     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
San Francisco |      46 |      50 | 0.25 | 1994-11-27
(1 row)

9.3 ordering;

You can ask the query returns a sorted:
mydb#SELECT * FROM weather
    ORDER BY city;

come to conclusion:
     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
Hayward       |      37 |      54 |      | 1994-11-29
San Francisco |      43 |      57 |    0 | 1994-11-29
San Francisco |      46 |      50 | 0.25 | 1994-11-27

In this example, the sort order is not absolutely clear, so you might see a line of San Francisco random order. However, if you use the following statement, then you will always get the results of the above
SELECT * FROM weather
    ORDER BY city, temp_lo;

You can ask the query results sorted in a certain order, and the elimination of duplicate rows output:
mydb#SELECT DISTINCT city
    FROM weather;

come to conclusion:
     city
---------------
Hayward
San Francisco
(2 rows)

Again, the result of the order of rows may be random.
10. view;

assume your application is particularly interested in the combined list of weather records and city location and you do not want to type the query each time. You can create a query on this view, it gives the query a name, you can refer to like an ordinary table. After entering the database, enter:
mydb#CREATE VIEW myview AS
    SELECT city, temp_lo, temp_hi, prcp, date, location
        FROM weather, cities
        WHERE city = name;

Establishment of view; then select the built view:
SELECT * FROM myview;
The results are as follows:
     city      | temp_lo | temp_hi | prcp |    date    | location 
---------------+---------+---------+------+------------+-----------
San Francisco |      46 |      50 | 0.25 | 1994-11-27 | (-194,53)
San Francisco |      43 |      57 |    0 | 1994-11-29 | (-194,53)
(2 rows)

11. Update the line;

you can update existing rows with the UPDATE command. Let's say you find all the number of thermometers November 28 have two degrees lower, you can update the data in the following way:
mydb#UPDATE weather
    SET temp_hi = temp_hi - 2,  temp_lo = temp_lo - 2
    WHERE date > '1994-11-28';

Look at the new state of the data:
SELECT * FROM weather;

The results are:
     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
San Francisco |      46 |      50 | 0.25 | 1994-11-27
San Francisco |      41 |      55 |    0 | 1994-11-29
Hayward       |      35 |      52 |      | 1994-11-29
(3 rows)

12. Delete rows;

rows DELETE command can be deleted from the table. Let's say you are no longer interested in the weather of Hayward, then you can delete those rows from the table using the following method:
mydb#DELETE FROM weather WHERE city = 'Hayward';

We use the form below statement must be careful
DELETE FROM tablename;

If there are no conditions, DELETE from the specified table to delete all the rows, it emptied. These systems do not ask you to confirm before!
13. With regard to article

on backing up and restoring databases will be introduced in PostgreSQL backup and recovery, we are referring to Chinese most of the information document, the purpose is to let the brothers find convenient, detailed documentation has something in Chinese, thank you brothers pointing :)
14. update log;

15. the reference documentation;

"PostgreSQL 8.1 Chinese documents"
16. Related documents

"Postgresql backup and restore ------ SQL dump chapter"
"PostgreSQL configuration file and user permissions"
"PostgreSQL database user authentication,"
"routine maintenance PostgreSQL database"

Reproduced in: https: //www.cnblogs.com/licheng/archive/2008/01/23/1050102.html

Guess you like

Origin blog.csdn.net/weixin_34055787/article/details/92630962