postgre 配置与连接代码

前端之家收集整理的这篇文章主要介绍了postgre 配置与连接代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

(1)从www.postgresql.org下载pgadmin3-1.6.2.zip 和 postgresql-8.2.3.tar.gz

前者是windows下管理端的安装包,后者是数据库的源码安装包。

(2)将postgresql-8.2.3.tar.gz拷贝指linux系统的一个临时目录中,解压缩

tar -zxvf postgresql-8.2.3.tar.gz

然后进入解压缩后的目录,

cd postgresql-8.2.3

进行安装配置:

#./configure

这样配置下来数据库将会安装到默认位置/usr/local/pgsql/下

#gmake

没有任何问题的话,我们可以看到最后一句提示信息

“All of Postgresql successfully made. Ready to install.”

#gmake install

成功安装后能看到最后一句提示信息"Postgresql installation complete."

cd /usr/local/

ls

我们能看到pgsql目录,里面有安装好的包

(3) 安装后环境设置:

用户添加:

#groupadd postgresql

#useradd -g postgresql postgresql

这时在/home目录下已经生成了postgresql目录,接着进行环境变量和profile的

修改

#cd /home/postgresql

#vi .bash_profile

文件添加

export PATH=$PATH:/usr/local/pgsql/bin

export MANPATH=$MANPATH:/usr/local/pgsql/man

export LD_LIBRARYPATH=$LD_LIBRARYPATH:/usr/local/pgsql/lib

然后保存退出

创建数据库目录和日志目录

mkdir /usr/local/pgsql/data

mkdir /usr/local/pgsql/log

touch /usr/local/pgsql/log/pgsql.log

改变属主:

chown -R postgresql:postgresql /usr/local/pgsql/data

chown -R postgresql:postgresql /usr/local/pgsql/log

chown -R postgresql:postgresql /usr/local/pgsql/log/pgsql.log

(4):初始化数据库并建立数据库用户

su - postgresql

initdb -D /usr/local/pgsql/data

现在就可以启动数据库

#pg_ctl -D /usr/local/pgsql/data -l /usr/local/pgsql/log/pgsql.log start

提示“server starting”

然后我们执行进程察看命令查看服务是否已经启动:

[postgresql@localhost ~]$ ps -A | grep postgres

19932 pts/1 00:00:00 postgres

19934 ? 00:00:00 postgres

19935 ? 00:00:00 postgres

说明数据库服务已经启动。

创建数据库

[postgresql@localhost ~]$ createdb psmp

提示"CREATE DATABASE"

创建用户

[postgresql@localhost ~]$ createuser -sADEP psmpAdmin

Enter password for new role:

Enter it again:

Shall the new role be allowed to create more new roles? (y/n) y

提示"CREATE ROLE"

其中-s 表示超级用户

我们设置密码为psmpPass

访问数据库

[postgresql@localhost ~]$ psql -d psmp -U psmpAdmin

然后就可以运行sql语句了,比如select或者insert之类

(5):接下来在windows上安装pgadmin1.6.2,也就是第一个包解压缩的EXE程序,这个比较简单。

当padmin安装完成后,你可能会急着去用这个管理工具连接后台数据库,可是你一定会遇到连接失败的问题,因为还有一些东西需配置

cd /usr/local/pgsql/data/目录下

可以看到有2个文件需要修改:pg_hba.conf 和 postgresql.conf

修改postgresql.conf 文件中listen_address为"*"并去掉前面的#注视符,对于有些版本的

数据库,比如我实用的7.4.16,只需要去掉tcpip_socket = true 和 port = 5432

前面的注视符,好了,保存;修改pg_hba.conf文件,在

# IPv4-style local connections:

host all all 127.0.0.1 255.255.255.255 trust

添加一行

host all all 192.168.1.3 255.255.0.0 trust

假如你的windows系统的IP为192.168.1.3

然后pg_ctl -D /usr/local/pgsql/data reload 重新加载配置

这时就可以从pgadmin连接进来了。

(6)C程序应用

建立一个序列数s_id

CREATE SEQUENCE s_id

INCREMENT 1

MINVALUE 1

MAXVALUE 9223372036854775807

START 20

CACHE 1;

ALTER TABLE s_id OWNER TO postgresql;

和一个表test:

CREATE TABLE test

(

id integer NOT NULL,

name character varying NOT NULL,

age integer NOT NULL,

CONSTRAINT test_pkey PRIMARY KEY (id)

)

WITH OIDS;

ALTER TABLE test OWNER TO postgresql;

C代码例子如下:

//test.cpp

#include "libpq-fe.h"

#include

#include

using namespace std;

static void exit_nicely(PGconn *conn)

{

PQfinish(conn);

exit(1);

}

int main()

{

int i,nFields,j;

struct pg_conn * conn = 0;

PGresult *res = 0;

conn = PQsetdbLogin("192.168.1.4","5432","","postgresql","postgresql");

if(PQstatus(conn) != CONNECTION_OK)

{

printf("connect fail /n");

}else

{

printf("connect success/n");

}

res = PQexec(conn,"BEGIN");

if(PQresultStatus(res) != PGRES_COMMAND_OK)

{

printf("execute sql fail %s",PQerrorMessage(conn));

PQclear(res);

exit_nicely(conn);

}

PQclear(res);

for(i = 0; i < 10; i++)

{

res = PQexec(conn,"insert into test(select nextval('s_id'),'dog',3)");

PQclear(res);

}

res = PQexec(conn,"DECLARE myportal CURSOR FOR select * from test where name = 'dog'");

//res = PQexec(conn,"select * from test where name = 'duanjigang'");

if (PQresultStatus(res) != PGRES_COMMAND_OK)

{

printf("DECLARE CURSOR Failed: %s",PQerrorMessage(conn));

PQclear(res);

exit_nicely(conn);

}

PQclear(res);

res = PQexec(conn,"FETCH ALL in myportal");

if (PQresultStatus(res) != PGRES_TUPLES_OK)

{

printf("FETCH ALL Failed: %s",PQerrorMessage(conn));

PQclear(res);

exit_nicely(conn);

}

nFields = PQnfields(res);

for (i = 0; i < nFields; i++)

printf("%-15s",PQfname(res,i));

printf("/n/n");

for (i = 0; i < PQntuples(res); i++)

{

for (j = 0; j < nFields; j++)

printf("%-15s",PQgetvalue(res,i,j));

printf("/n");

}

PQclear(res);

res = PQexec(conn,"delete from test where name = 'dog'");

PQclear(res);

res = PQexec(conn,"CLOSE myportal");

PQclear(res);

res = PQexec(conn,"END");

PQclear(res);

PQfinish(conn);

return 0;

}

Makefile

#!/bin/sh

default:

g++ -c test.cpp -I /usr/local/pgsql/include/

g++ -o test test.o -L/usr/local/pgsql/lib -lpq

clean:

rm -fr test test.o

可能在链接或者运行时提示不能打开libpq这个库,你需要修改/etc/ld.so.conf文件,并在中添加/usr/local/pgsql/lib,然后执行ldconfig命令,再次运行./test就能看到sql语句的数出了

具体的文档可以去CU的中文文档察看,postgresql安装包doc中也有详细的说明。

/////////////////////////////////////////////////////////////连接与执行代码/////////////////////////////////////////////////

/***************************************************************************
* Copyright (C) 2005 by 北京宽广电信高技术发展有限公司
*
* PROJ. NAME : TMA
* DATE : 2006/10/24
* VERSION : 1.0
* AUTHOR : Longlimei
* DESCR. :
* MODIFY HISTORY :
*
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include <netinet/in.h>
#include <arpa/inet.h>
//#include "moduleintf.h"

#include "pqCopy.h"
//#include "UtilityFunc.h"
//#include "logmsg.h"

extern char pDBServer[128];
extern char g_strDBName[128];
extern char pDBUser[128];
extern char pDBPwd[128];
extern int g_nClientEncoding;

// char pDBServer[STR_LEN+1];
// char g_strDBName[STR_LEN +1];
// char pDBUser[STR_LEN+1];
// char pDBPwd[STR_LEN+1];
// int g_nClientEncoding;


using namespace std;

void getIpString(const unsigned long &host,char *pTmp)
{
char *p = NULL;

struct in_addr struAddr ;
struAddr.s_addr = host;
p = inet_ntoa(struAddr);
strncpy(pTmp,p,63);
}
/**************************************************
* 功能: 建立DB的连接
* 参数:
* 返回:
* 说明:
* ************************************************/
PGconn* connectDB(unsigned long host,unsigned short port,
char *pDatabase,char *pUID,char *pPWD,unsigned short timeout)
{
int IntTemp;
char command[128] = {0};
char conninfo[128];
char *pStrError = NULL;

PGresult *res = NULL;

//construct conninfo

char pTmp[64]={0};
char *pIP = NULL;
if (host == 0)
{
pIP = pDBServer;
}
else
{
getIpString(host,pTmp); // 1?
pIP = pTmp;
}

if (0 == port)
sprintf(conninfo,"hostaddr=%s port=5432",pIP);
else
sprintf(conninfo,"hostaddr=%s port=%d",pIP,port);

strcat(conninfo," dbname=");

if (NULL != pDatabase)
strcat(conninfo,pDatabase);
else
strcat(conninfo,g_strDBName);

strcat(conninfo," user=");
if (NULL != pUID)
strcat(conninfo,pUID);
else
strcat(conninfo,pDBUser);

strcat(conninfo," password=");
if (NULL != pUID)
strcat(conninfo,pPWD);
else
strcat(conninfo,pDBPwd);

strcat(conninfo," connect_timeout=");
sprintf(pTmp," %d",timeout);
strcat(conninfo,pTmp);

//open connection to db
PGconn* conn = PQconnectdb(conninfo);
IntTemp = PQstatus(conn);
if (IntTemp != CONNECTION_OK)
{
pStrError = PQerrorMessage(conn);
LOG( conninfo);
LOG( pStrError);

// 2012-02-16 释放资源
if(NULL != conn)
{
PQfinish(conn);
}

conn = NULL;
goto FUNCTION_EXIT;
}

if (g_nClientEncoding == CHAR_ENCODING_UTF8)
strcpy(command,"set client_encoding = 'UTF8';");
else
strcpy(command,"set client_encoding = 'GBK';");
res = PQexec(conn,command);

PQclear(res);

FUNCTION_EXIT:
return conn;
}

/**************************************************
* 功能: 建表
* 参数:
* pDBconn  : I,DB连接。若为NULL,则临时建立连接。如果是外部提供的,则由外部负责释放
* ulDBServer: I,DB的IP地址
* pDBName : I,DB的数据库
* psql : I, sql to execute
* 返回:
* 说明:
* ************************************************/
PQCopyRsltEnum executesql(PGconn* pDBconn,unsigned long ulDBServer,char *pDBName,char *psql)
{
PQCopyRsltEnum EnumFailed = PQCOPY_Failed_OTHER;

bool BoolOwn = false;
PGconn *pConn = pDBconn;
PGresult *res = NULL;

if(NULL == pConn)
{
BoolOwn = true;
pConn = connectDB(ulDBServer,pDBName);
}

if(NULL == pConn)
{
EnumFailed = PQCOPY_Failed_CONN;
goto FUNCTION_EXIT;
}

res = PQexec(pConn,psql);
if ( PQresultStatus(res) != PGRES_COMMAND_OK ) // 成功完成一个不返回数据的命令
{
EnumFailed = PQCOPY_Failed_EXEC;
goto FUNCTION_EXIT;
}

EnumFailed = PQCOPY_SUCCESS;

FUNCTION_EXIT:
if ( (NULL != pConn) && (PQCOPY_SUCCESS != EnumFailed) )
{
char *pStrError = PQerrorMessage(pConn);
LOG( psql);
LOG( pStrError);
}

if ( NULL != res )
{
PQclear(res);
}

if(NULL != pConn && BoolOwn) { PQfinish(pConn); } return EnumFailed; }

原文链接:https://www.f2er.com/postgresql/196637.html

猜你在找的Postgre SQL相关文章