C连接postgresql Dome
#include<stdio.h>
#include<stdlib.h>
/*libpq-fe.h在/postgresql-13.1/include文件下,放到/usr/include*/
#include<libpq-fe.h>
#include<string.h>
int main(int argc, char** argv) {
/*定义用于连接数据库的常量字符串,填自己的ip,端口,用户,数据库,密码*/
const char *conninfo="host=localhost port=5433 user=postgres dbname=postgres password=123789..";
/*与数据库服务器建立连接*/
PGconn *conn=PQconnectdb(conninfo);
/*判断数据库连接是否成功,PQstatus()方法返回链接状态的枚举,连接正常则打印CONNECTION OK*/
if(PQstatus(conn)==CONNECTION_OK){
printf("connection ok\n");
}
else
{
fprintf(stderr,"%s",conninfo);
PQerrorMessage(conn);
printf("connection error");
PQfinish(conn);
}
/*字符串拼接*/
char commands[100];
char age[20];
char command[100] = "select * from test where age = ";
printf("please input condition,age:");
scanf("%s",age);
strcat(commands,command);
strcat(commands,age);
printf("%s\n",commands);
PGresult *res = PQexec(conn,commands);
//PGresult *res = PQexec(conn,"SELECT * FROM test");
/**运行查询命令*/
if( PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr,"Exec Query Fauled!\n");
PQclear(res);
return 0;
}
int i;
int t;
int k;
int s;
i = PQntuples(res);
/**取得查询的结果的记录的数量*/
t = PQnfields(res);
/**取得字段数量*/
for(s=0; s<i;s++) {
for (k = 0; k<t; k++) {
printf("%s",PQgetvalue(res,s,k));
printf(" ");
}
printf("\n");
}
PQfinish(conn);
PQclear(res);
return 0;