转载请注明本文出处,LeonidasFlames的blog ,链接:Linux下PostgreSQL数据库C语言接口:libpq (二)
二、libpq库下C语言程序对PostgreSQL的访问
首先看一个程序示例:
#include <iostream>
#include <libpq-fe.h>
using namespace std;
int main(void)
{
数据库连接
const char* conninfo="hostaddr=127.0.0.1 user=Meme dbname=MyDatabase password=123";
PGconn* conn=PQconnectdb(conninfo);
if(PQstatus(conn)==CONNECTION_BAD)
{
cout<<"连接数据库失败!"<<endl;
PQfinish(conn);
return 1;
}
数据库SELECT查询
PGresult* res=PQexec(conn,"SELECT *FROM student");
if(PQresultStatus(res)!=PGRES_TUPLES_OK)
{
cout<<"SELECT查询失败!"<<endl;
cout<<PQresultErrorMessage(res)<<endl;
PQclear(res);
return 1;
}
int i=PQntuples(res);
int t=PQnfields(res);
for(int s=0;s<i;s++)
{
for(int k=0;k<t;k++)
{
cout<<PQgetvalue(res,s,k);
cout<<" ";
}
cout<<endl;
}
PQclear(res);
/数据库DELETE操作
res=PQexec(conn,"DELETE FROM student WHERE id=1001");
if(PQresultStatus(res)!=PGRES_COMMAND_OK)
{
cout<<"DELETE语句执行失败!"<<endl;
cout<<PQresultErrorMessage(res)<<endl;
PQclear(res);
return 1;
}
else
{
cout<<