Click here to Skip to main content
15,887,027 members
Articles / Programming Languages / C

Accessing: PostgreSql data base using libpq - C Library.

Rate me:
Please Sign up or sign in to vote.
4.65/5 (12 votes)
18 May 2009CPOL2 min read 68.9K   2K   26  
A set of class to access and manipule PostgreSql data base using libpq - C Library.
// psql.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <winsock2.h> 
#include "db/PostgreSql.h"

int _tmain(int argc, _TCHAR* argv[])
{
	try
	{
		ResultSet rs1, rs2;
		std::vector<std::string> row;

		DataBase<PostgreSql> dataBase("127.0.0.1", "sa", "pwd", "test");

		dataBase << "DROP TABLE tblTest1";
		dataBase <<	"CREATE TABLE tblTest1(test char(15) NOT NULL, testInt INT NULL, Constraint PK Primary Key(test))";
		dataBase << "DELETE FROM tblTest1";

		dataBase << "INSERT INTO tblTest1(test, testInt) VALUES('00', 1)" ;
		dataBase << "INSERT INTO tblTest1(test) VALUES('01')" ;
		dataBase << "INSERT INTO tblTest1(test) VALUES('02')" ;
		dataBase << "INSERT INTO tblTest1(test) VALUES('03')" ;

		dataBase << "DROP TABLE tblTest2";
		dataBase <<	"CREATE TABLE tblTest2(test char(15) NOT NULL, dt DATE NULL)";
		dataBase << "DELETE FROM tblTest2";

		dataBase << "INSERT INTO tblTest2(test, dt) VALUES('01', '1979/11/14')" ;
		dataBase << "INSERT INTO tblTest2(test) VALUES('02')" ;
		dataBase << "INSERT INTO tblTest2(test) VALUES('03')" ;
		dataBase << "INSERT INTO tblTest2(test) VALUES('04')" ;

		dataBase << "SELECT * FROM tblTest1, tblTest2 WHERE tblTest1.test = tblTest2.test", rs1;
		dataBase << "SELECT * FROM tblTest2 WHERE test = '01'", rs2;

		std::string value;

		while(rs1.fetch(0, value))
		{
			std::cout << value << std::endl;
		}

		while(rs2.fetch(1, value))
		{
			std::cout << value << std::endl;
		}

		while(rs1.fetch(row))
		{
			for (size_t i = 0; i < row.size(); i++)
			{
				std::cout << row[i] <<  " | ";
			}
		}

		while(rs2.fetch(row))
		{
			for (size_t i = 0; i < row.size(); i++)
			{
				std::cout << row[i] << " | ";
			}
		}

		std::cout << rs1.get(0)[0] << " | " << rs1.get(0)[1] << std::endl;
		std::cout << rs2.get(0, 1) << std::endl;

	
	}
	catch (const DataBaseError& e)
	{
		std::cout << e.what() << std::endl;
	}

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions