postgres数据库开发笔记

PostgreSQL连接C/C++接口实例

http://www.yiibai.com/html/postgresql/2013/080894.html


库使用介绍,常用SQL语句,提供库使用示例,使用c/c++ 访问 postgres 数据库,使用 SQL标准语句是一个不错的选择。

本文记录一个资料链接,以备后用。 先看上面链接中的介绍和各个语句的使用方法,下面的工程,linux上和windows上环境搭建好了之后,可以直接使用。


wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gz
tar xvfz libpqxx-4.0.tar.gz
cd libpqxx-4.0
./configure
make
make install yiib


示例测试代码:


#include <iostream>
#include <pqxx/pqxx>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace pqxx;



#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[])
{
   char * sql;

   try{
      connection C("dbname=streamMediaDataBase user=postgres password=cdzchx \
      hostaddr=127.0.0.1 port=5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }
      /* Create SQL statement */

//      sql =
//      "INSERT INTO STREAM_MEDIA_INFO (CHANNEL,RTSPURL,RTMPURL,PUSHPID,TIPS,SRCALIVE) VALUES (6, 'rtsp://1111', 'rtmp://1111', 1111, 'notips',true ) \
//      ,(7, 'rtsp://1111', 'rtmp://1111', 1111, 'notips',true )\
//      ,(8, 'rtsp://1111', 'rtmp://1111', 1111, 'notips',true )\
//      ,(9, 'rtsp://1111', 'rtmp://1111', 1111, 'notips',true )\
//    		  ";

//      sql =(char*)
//          "SELECT * FROM STREAM_MEDIA_INFO WHERE\
//          channel>0\
//        		  ";
//

      sql =(char*)
          "UPDATE STREAM_MEDIA_INFO SET rtmpurl='rtmp://woshiceshi'  WHERE\
          channel=0\
        		  ";

          /* Create a transactional object. */
          work W(C);


          /* Execute SQL query */
          pqxx::result ret  = W.exec( sql );
    		W.commit();

    		for (pqxx::result::const_iterator row = ret.begin(); row != ret.end(); ++row)
    		{

    			for (pqxx::tuple::const_iterator field = row->begin();field != row->end();++field)
    			{
    				printf(" %s: %s \n", field.name() ,field->c_str() );

    			}
    			std::cout << std::endl;
    		}

		C.disconnect ();


	}catch (const std::exception &e){
		cerr << e.what() << std::endl;
		return 1;
	}

	return 0;
}


封装后的代码:

cpp文件:

#include <PostGres.h>


postGresConnector_c::postGresConnector_c(const char* dbname_,const char* usr_,const char* passwd_,
		const char* hostaddr_,const char* port_,list<string> table_list_)
:m_dbConnection(NULL),m_dbWork (NULL)
{
	this->InitialPostGresConnector( dbname_, usr_, passwd_, hostaddr_, port_,table_list_);
	this->ConnectDB();
}
postGresConnector_c::~postGresConnector_c()
{

}
void postGresConnector_c::InitialPostGresConnector(const char* dbname_,const char* usr_,const char* passwd_,
		const char* hostaddr_,const char* port_,list<string> table_list_)
{
	assert( dbname_!=NULL &&  usr_!=NULL && passwd_!=NULL && hostaddr_!=NULL && port_!=NULL);

	strcpy(m_postGresConnectorInfo.dbname,dbname_);
	strcpy(m_postGresConnectorInfo.hostaddr,hostaddr_);
	strcpy(m_postGresConnectorInfo.passwd,passwd_);
	strcpy(m_postGresConnectorInfo.port,port_);
	strcpy(m_postGresConnectorInfo.usr,usr_);

	m_postGresConnectorInfo.table_list = table_list_ ;

}
bool postGresConnector_c::ConnectDB()
{
	try{
		char CMD[2048];
		sprintf(CMD,"dbname=%s user=%s password=%s hostaddr=%s port=%s",
				m_postGresConnectorInfo.dbname,
				m_postGresConnectorInfo.usr,
				m_postGresConnectorInfo.passwd,
				m_postGresConnectorInfo.hostaddr,
				m_postGresConnectorInfo.port);
	  m_dbConnection = new connection(CMD);

	  if (m_dbConnection->is_open()) {
		 cout << "Opened database successfully: " << m_dbConnection->dbname() << endl;
		 return false ;
	  } else {
		 cout << "Can't open database" << endl;
		 return true;
	  }

	}catch (const std::exception &e){
		cerr << e.what() << std::endl;
		return 1;
	}
}
void postGresConnector_c::Disconnect()
{
	if(m_dbConnection!=NULL)
		m_dbConnection->disconnect ();
}
void postGresConnector_c::DoSQL_SQLSentence(const char* sentence_)
{
	try{
		if(!m_dbConnection)
			return ;
		/* Create a transactional object. */
		work W(*m_dbConnection);

		/* Execute SQL query */
		W.exec( sentence_ );
		W.commit();

	}catch (const std::exception &e){
		Fprint_String(e.what(),"StdError","a+");
		cerr << e.what() << std::endl;
	}
}
pqxx::result postGresConnector_c::DoSQL_SELECTALL(const char* tableName_)
{
	try{
		char sql[1024] ;
		sprintf(sql,"SELECT * FROM %s ",tableName_);

		/* Create a transactional object. */
		work W(*m_dbConnection);

		/* Execute SQL query */
		pqxx::result ret  = W.exec( sql );
		W.commit();

		for (pqxx::result::const_iterator row = ret.begin(); row != ret.end(); ++row)
		{

			for (pqxx::tuple::const_iterator field = row->begin();field != row->end();++field)
			{
				printf(" %s: %s \n", field.name() ,field->c_str() );

			}
			std::cout << std::endl;
		}
		return ret ;
	}catch (const std::exception &e){
		Fprint_String(e.what(),"StdError","a+");
		cerr << e.what() << std::endl;
	}
}








int main_post()
{
	char SQLSentence[2048];
	printf("Test dbConnector \n");

	list<string> tableList ;
	tableList.push_front("stream_media_info");
	tableList.push_front("stream_media_info2");
	tableList.push_front("stream_media_info3");


	postGresConnector_c tmpPostGresConnector("streamMediaDataBase","postgres","cdzchx","127.0.0.1","5432",tableList);
//	tmpPostGresConnector.DoSQL_SELECTALL("stream_media_info");

	tableList.pop_back();
	tableList.pop_back();

	tmpPostGresConnector.ShowTableList();
	/*
	 * 	INSERT INTO __ (__,__,__) VALUES (__,__,__),(__,__,__)
	 *	DELETE FROM __ WHERE __=__
	 *	SELECT * FROM __
	 *	UPDATE __ SET __=__
	 * */
//	sprintf(SQLSentence,"INSERT INTO STREAM_MEDIA_INFO (CHANNEL,RTSP_URL,RTMP_URL,PUSH_PID,TIPS,SRC_ALIVE)\
//			 VALUES (10,'rtsp://woshi:rrtt','rtmp://woshirtttmmmppp',1234,'want tips?',true),\
//			(11,'rtsp://woshi:rrtt','rtmp://woshirtttmmmppp',1234,'want tips?',true)\
//			\
//			");
//	sprintf(SQLSentence,"DELETE FROM STREAM_MEDIA_INFO WHERE channel=11\
//			 \
//			\
//			\
//			");
	sprintf(SQLSentence,"UPDATE STREAM_MEDIA_INFO SET rtmp_url='rtmp://wolaishishirtmpceshi!' WHERE channel=11\
			 \
			\
			\
			");
	tmpPostGresConnector.DoSQL_SQLSentence(SQLSentence);
}

头文件:

#ifndef POSTGRES_H_
#define POSTGRES_H_

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <pqxx/pqxx>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <string>

using namespace std;
using namespace pqxx;


#include <iostream>
#include <pqxx/pqxx>
#include <list>

#include <systemfun.h>

using namespace std;
using namespace pqxx;



typedef struct
{
	char dbname[1024];
	char usr[1024];
	char passwd[1024];
	char hostaddr[1024];
	char port[1024];
	list<string>	table_list ;

}postGresConnectorInfo;

/*
 * 	INSERT INTO __ (__,__,__) VALUES (__,__,__),(__,__,__)
 *	DELETE FROM __ WHERE __=__
 *	SELECT * FROM __
 *	UPDATE __ SET __=__
 * */

class postGresConnector_c
{
public:
	postGresConnector_c(const char* dbname_,const char* usr_,const char* passwd_,
			const char* hostaddr_,const char* port_,list<string> table_list_) ;
	~postGresConnector_c();

	list<string>* GetAttribute_tablelist(){return &m_postGresConnectorInfo.table_list ;}
	char* GetAttribute_dbname(){return m_postGresConnectorInfo.dbname;}
	char* GetAttribute_usr(){return m_postGresConnectorInfo.usr;}
	char* GetAttribute_passwd(){return m_postGresConnectorInfo.passwd;}
	char* GetAttribute_hostaddr(){return m_postGresConnectorInfo.hostaddr;}
	char* GetAttribute_port(){return m_postGresConnectorInfo.port;}

	void PushFrontTableList(string tableList_){m_postGresConnectorInfo.table_list.push_front(tableList_);}
	void PopBackTableList(){m_postGresConnectorInfo.table_list.pop_back();}
	void ShowTableList(){
		list<string>::iterator iter;
		for(iter=m_postGresConnectorInfo.table_list.begin();iter!=m_postGresConnectorInfo.table_list.end();++iter){
			printf("%s\n",iter->c_str());
		}
	}

	pqxx::result DoSQL_SELECTALL(const char* tableName_);
	void DoSQL_SQLSentence(const char* sentence_) ;

private:
	void InitialPostGresConnector(const char* dbname_,const char* usr_,const char* passwd_,
			const char* hostaddr_,const char* port_,list<string> table_list_);
	bool ConnectDB();
	void Disconnect() ;
private:
	postGresConnectorInfo	m_postGresConnectorInfo ;
	connection 				*m_dbConnection ;
	work					*m_dbWork ;
};



#endif /* POSTGRES_H_ */















你可能感兴趣的:(教程,postgres)