之前没怎么接触各类数据库,现在对新上手的数据库都来学习一番,项目组经常用到的数据库和新使用的数据库都会做个笔记,本篇讲讲postgresql。
1、安装postgresql
参考网址:https://blog.csdn.net/DaSo_CSDN/article/details/75330009
环境:CentOS Linux release 7.5.1804 x86_64
yum install https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpm
yum install -y postgresql96-server postgresql96-contrib
输入/usr/pgsql-9.6/bin/postgresql96-setup initdb
并回车,初始化数据库
输入systemctl start postgresql-9.6
并回车,启动服务
修改默认用户名和密码:
输入su - postgres
并回车,切换至用户。
输入psql -U postgres
并回车,登录数据库。
输入ALTER USER postgres with encrypted password 'abcdef';
(不要漏了“;”)并回车,设置默认用户postgre的密码,此处密码为abcdef
,可自行修改。
输入\q
并回车, 退出数据库。
输入exit
并回车,退出用户。
配置远程访问:
输入vi /var/lib/pgsql/9.6/data/postgresql.conf
并回车。
(如果使用其他版本的PostgreSQL则需要把其中的9.6
换成对应的版本)
光标下翻,找到listen_addresses
。如果想对所有IP开放,则将localhost
改为*
即可,如果想仅对部分IP开放,多个IP之间用,
(逗号+空格)隔开。
输入vi /var/lib/pgsql/9.6/data/pg_hba.conf
并回车,将光标移至底部。
按i键进入插入编辑模式,在IPv4 local connections
下方添加允许连接的IP。
如果想允许所有IPv4地址,则加入一行host all all 0.0.0.0/0 md5
。IPv6方法类似
输入systemctl restart postgresql-9.6.service
并回车,重启服务。
2、基本使用
参考网址:http://www.postgres.cn/docs/9.5/tutorial-accessdb.html
create database testdb;
\l 列出当前数据库 \c 切换数据库 \d 列出表 \h \q
createdb/dropdb xxx;
SELECT version(); SELECT current_date;
3、libpq-c库
参考网址:http://www.postgres.cn/docs/9.5/libpq.html
一个应用程序可以在一个时刻打开多个后端连接(原因之一就是为了访问多个数据库)。每个连接用一个PGconn对象表示,它从函数PQconnectdb
、PQconnectdbParams
或PQsetdbLogin
得到。注意这些函数将总是返回一个非空的对象指针,除非正好没有内存来分配PGconn对象。在通过该连接对象发送查询之前,应该调用PQstatus
函数来检查返回值以确定是否得到了一个成功的连接。