1. 程式人生 > >Windows環境下C/C++訪問PostgreSQL資料庫

Windows環境下C/C++訪問PostgreSQL資料庫

轉載自:https://segmentfault.com/a/1190000000628234

PostgreSQL是一款在Linux環境下應用十分廣泛的輕量級關係型資料庫,大家都聽說過MySQL,卻對PostgreSQL鮮有耳聞,它其實在效能、應用領域上和MySQL不相上下。網上關於Windows環境下C/C++訪問PostgreSQL資料庫的資料很少,文字分析了C/C++訪問PostgreSQL資料庫的過程。

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

1、環境配置
(1)文字使用的IDE是VS2013,我們需要配置包含目錄(include)、庫目錄(lib)、連結器輸入附加依賴(libpq.lib);

(2)工程目錄下需要加入4個dll檔案(libeay32.dlllibintl.dlllibpq.dllssleay32.dll),這些檔案都能在PostgreSQL安裝目錄下找到;
(3)工程cpp檔案中加入標頭檔案#include <libpq-fe.h>libpq-fe.h標頭檔案包含了API介面函式宣告及註釋,下面介紹的函式在libpq-fe.h中都能找到。

2、連線資料庫
(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函式顯示出錯資訊。

封裝成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;
    }
}

3、執行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開始;

封裝成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;
        }
    }

}

4、關閉連線
(1)查詢集清理函式
extern void PQclear(PGresult *res)
res:查詢集指標;
(1)關閉連線函式
extern void PQfinish(PGconn *conn)
conn:連線指標;

5、錯誤查詢
許多時候執行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;

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