C基于 postgresql-devel 连接postgresql 数据库,实现增删改查的代码封装

  • yum install postgresql-devel 安装连接postgresql 相关的库
  • 编写 main.c
  • 使用 gcc -g main.c -o main -I /usr/include -L /usr/lib64 -lpq 编译, 参数详解
  • ./main.exe 执行

2. main.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/** yum install postgresql-devel */
#include <libpq-fe.h>
#include <string.h>
const char *conninfo="host=192.168.31.140 dbname=sfang user=postgres password=13673711016";
void displayResult(const PGresult *res)
{
	assert(NULL != res);

	int nfields = PQnfields(res);
	int ntuples = PQntuples(res);
    if(0 == ntuples || 0 == ntuples) { return ;} 
	int rows = 0;
	int cols = 0;
	for (cols = 0; cols < nfields; ++cols)
	{
		fprintf(stdout, "| %s", PQfname(res, cols));
	}
	fprintf(stdout, "|\n");

	for (rows = 0; rows < ntuples; ++rows)
	{
		for (cols = 0; cols < nfields; ++cols)
		{
			fprintf(stdout, "| %s", PQgetvalue(res, rows, cols));
		}
		fprintf(stdout, "|\n");
	}
}

PGconn * getConnection() {
    PGconn *conn = PQconnectdb(conninfo);
    if(PQstatus(conn) == CONNECTION_BAD)
    {
       fprintf(stderr,"connection to %s failed \n",conninfo);
       exit(-1);
    }
    return conn;
}
/** create table or update table sql */
int execSql(const char * sql, void * fun_sucess_name) {    
    PGconn *conn = getConnection();
    PGresult *res;
    res = PQexec(conn, sql);
    if (PGRES_TUPLES_OK != PQresultStatus(res)){
        fprintf(stderr, "#ERR-PGSQL: sql exec failed : %s \n", PQerrorMessage(conn));
        PQclear(res);          
    }else {
        if(NULL != fun_sucess_name) {
            void (* fun_sucess)(const PGresult *res) = fun_sucess_name;
            fun_sucess(res);
        }
    }
    PQfinish(conn);
}

//gcc -g main.c -o main -I /usr/include -L /usr/lib64 -lpq
int main(int argc, char const *argv[])
{
    // execSql( "CREATE TABLE c_test_table("  \
    //             "ID INT PRIMARY KEY     NOT NULL," \
    //             "NAME           TEXT    NOT NULL," \
    //             "AGE            INT     NOT NULL," \
    //             "ADDRESS        CHAR(50)," \
    //             "SALARY         REAL );", NULL);

    execSql("select * from c_test_table", displayResult);

    execSql("update c_test_table set address = '南京市1' where id = 1;", displayResult);

    execSql("select * from c_test_table  where id = 1", displayResult);
}
上一篇:2021-10-03


下一篇:Docker详解