Linux下PostgresQL数据库C语言接口:libpq (二)数据库访问

这篇博客介绍了如何利用libpq库在Linux环境下用C语言连接并操作PostgreSQL数据库,包括执行SQL语句、获取查询结果、处理记录和字段、错误处理等功能。示例代码展示了不同函数的使用方法,如PQexec、PQsendQuery、PQgetResult等。
摘要由CSDN通过智能技术生成

转载请注明本文出处,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<<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值