Windows環境下C/C++訪問PostgreSQL數據庫

PostgreSQL是一款在Linux環境下應用十分普遍的輕量級關係型數據庫,你們都據說過MySQL,卻對PostgreSQL鮮有耳聞,它其實在性能、應用領域上和MySQL不相上下。網上關於Windows環境下C/C++訪問PostgreSQL數據庫的資料不多,文本分析了C/C++訪問PostgreSQL數據庫的過程。php

Windows環境C/C++訪問PostgreSQL主要有兩種方式:利用Qt封裝的數據庫訪問組件、利用PostgreSQL的API函數。使用Qt平臺訪問PostgreSQL的侷限性很大,一旦脫離了訪問組件,數據庫就沒法操做。使用數據庫自帶的API函數訪問數據庫具備較好的性能,可是API函數操做、理解比較難,網上相關資料少時須要閱讀API文檔。html

一、環境配置
(1)文本使用的IDE是VS2010,咱們須要配置包含目錄(include)、庫目錄(lib)、連接器輸入附加依賴(libpq.lib);
QQ截圖20140715172437.jpg
QQ截圖20140715172612.jpgsql

(2)工程目錄下須要加入4個dll文件(libeay32.dlllibintl.dlllibpq.dllssleay32.dll),這些文件都能在PostgreSQL安裝目錄下找到;
(3)工程cpp文件中加入頭文件#include <libpq-fe.h>libpq-fe.h頭文件包含了API接口函數聲明及註釋,下面介紹的函數在libpq-fe.h中都能找到。數據庫

二、鏈接數據庫
(1)數據庫鏈接函數函數

extern PGconn *PQsetdbLogin(const char *pghost, const char *pgport,
             const char *pgoptions, const char *pgtty,
             const char *dbName,
             const char *login, const char *pwd);

返回值PGconn *指針,即鏈接指針。若是你要對PQsetdbLogin函數封裝的話,記得將形參鏈接指針設成PGconn *&引用類型,由於鏈接函數須要對鏈接指針修改,而不是修改對象!
pghost:主機地址,本機爲127.0.0.1localhost
pgport:端口值,通常爲5432;
pgoptions:額外選項,NULL便可;
pgttyNULL便可;
dbName:數據庫名;
user:用戶名;
pwd:密碼;工具

(2)錯誤顯示函數
extern char *PQerrorMessage(const PGconn *conn)
當鏈接有誤時,可使用PQerrorMessage函數顯示出錯信息。post

封裝成ConnectToDB函數:性能

bool ConnectToDB(PGconn *&conn,char *pghost,char *pgport,char *dbname,char *user,char *pwd)
{
    //pgoptions、pgtty參數默認爲NULL
    char *pgoptions,*pgtty;
    pgoptions=NULL;
    pgtty=NULL;

    conn=PQsetdbLogin(pghost,pgport,pgoptions,pgtty,dbname,user,pwd);
    if(PQstatus(conn)==CONNECTION_BAD) // or conn==NULL 
    {
        cout<<"Connection db "<<dbname<<" failed!"<<endl;
        cout<<PQerrorMessage(conn)<<endl;
        return false;
    }
    else
    {
        cout<<"Connection db "<<dbname<<" success!"<<endl;
        return true;
    }
}

三、執行SQL語句
執行SQL語句主要是增刪改查,只有查詢會返回有效記錄集。
(1)SQL執行函數
extern PGresult *PQexec(PGconn *conn, const char *query)
返回值PGresult *:查詢集指針;
conn:鏈接指針;
query:SQL語句;
(2)元組數函數
extern int PQntuples(const PGresult *res)
返回值:查詢集中記錄數;
res:查詢集指針;
(3)字段數函數
extern int PQnfields(const PGresult *res)
返回值:每條記錄中列數(字段數);
res:查詢集指針;
(4)取值函數
extern char *PQgetvalue(const PGresult *res, int tup_num, int field_num);
返回值:查詢集中每一個位置的值;
res:查詢集指針;
tup_num:行號,從0開始;
field_num:列號,從0開始;spa

封裝成ExecSQL函數:指針

bool ExecSQL(PGconn *conn,const char *sql)
{
    PGresult *res=NULL;
    if(conn==NULL)
    {
        cout<<"Conn is null"<<endl;
        return false;
    }
    else
    {
        res=PQexec(const_cast<PGconn *>(conn),sql);
        if(res==NULL)
        {
            return false;
        }
        else
        {
            // 輸出記錄
            int tuple_num=PQntuples(res);
            int field_num=PQnfields(res);
            for(int i=0;i<tuple_num;++i)
            {
                for(int j=0;j<field_num;++j)
                    cout<<PQgetvalue(res,i,j)<<" ";
                cout<<endl;
            }

            ClearQuery(res);
            return true;
        }
    }

}

四、關閉鏈接
(1)查詢集清理函數
extern void PQclear(PGresult *res)
res:查詢集指針;
(1)關閉鏈接函數
extern void PQfinish(PGconn *conn)
conn:鏈接指針;

五、錯誤查詢
許多時候執行SQL語句後,數據表沒有變化,程序也不報錯,這種狀況很難發現錯誤。咱們須要使用PostgreSQL提供的errorMessagestatus函數追蹤程序變量的狀態。
好比:
(1)PQerrorMessage函數提供了PGconn鏈接指針的出錯信息;
(2)PQresultErrorMessage函數提供了PGresult查詢集指針的出錯信息;
(3)PQresultStatus函數返回查詢集指針的狀態信息ExecStatusType,這是個枚舉enum類型:

typedef enum
{
    PGRES_EMPTY_QUERY = 0,      /* empty query string was executed */
    PGRES_COMMAND_OK,           /* a query command that doesn't return
                                 * anything was executed properly by the
                                 * backend */
    PGRES_TUPLES_OK,            /* a query command that returns tuples was
                                 * executed properly by the backend, PGresult
                                 * contains the result tuples */
    PGRES_COPY_OUT,             /* Copy Out data transfer in progress */
    PGRES_COPY_IN,              /* Copy In data transfer in progress */
    PGRES_BAD_RESPONSE,         /* an unexpected response was recv'd from the
                                 * backend */
    PGRES_NONFATAL_ERROR,       /* notice or warning message */
    PGRES_FATAL_ERROR,          /* query failed */
    PGRES_COPY_BOTH,            /* Copy In/Out data transfer in progress */
    PGRES_SINGLE_TUPLE          /* single tuple from larger resultset */
} ExecStatusType;

有了這些工具,發現錯不是難事!

最後附上PostgreSQL中文文檔:PostgreSQL DocumentAPI接口文檔
文章來源:http://tanhp.com/index.php/archives/208/

相關文章
相關標籤/搜索