linux C++連接數據庫postgreSql

mx3y 9年前發布 | 1K 次閱讀 C/C++

linux C++連接數據庫postgreSql,在centos6.3,eclipse下調試成功

#include <stdio.h>

include <stdlib.h>

include <libpq-fe.h>

int main(int argc, char argv[]) { PGconn conn; PGresult dataset; ConnStatusType pgstatus; char connstr[1024]; char szSQL[2048]; char paramValues = NULL; int nParams = 0;

sprintf(connstr, "hostaddr=%s dbname=%s port=%d user=%s password=%s",
        "192.168.192.168", "test", 5432, "testuser", "123456");
conn = PQconnectdb(connstr);
pgstatus = PQstatus(conn);
if (pgstatus == CONNECTION_OK)
{
    printf("Connect database success!\n");
}
else
{
    printf("Connect database fail:%s\n", PQerrorMessage(conn));
    return 1;
}

sprintf(szSQL, "insert into tmptable(a,name) values(1,'aaaaaa')");
dataset = PQexecParams(conn, szSQL, nParams, /* 參數個數 */
NULL, /* 讓后端推出參數類型 */
(const char * const *) paramValues, NULL, /* 因為是文本,所以必須要參數長度 */
NULL, /* 缺省是全部文本參數 */
0); /* 是否是二進制結果 */

if ((PQresultStatus(dataset) == PGRES_COMMAND_OK)
        || (PQresultStatus(dataset) == PGRES_TUPLES_OK))
{
    printf("Successfully execute SQL : %s\n", szSQL);
}
else
{
    printf("%s\n", PQerrorMessage(conn));
}

/* 關閉數據庫連接并清理 */
PQfinish(conn);
return 0;

}</pre>

 本文由用戶 mx3y 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!