📅  最后修改于: 2023-12-03 15:03:50.118000             🧑  作者: Mango
PostgreSQL-C C++接口是一个用于在C++程序中连接和操作PostgreSQL数据库的接口库。C++开发人员可以使用该库来加快数据库开发工作,并且在程序性能和数据库性能方面都有很好的表现。
在使用该库之前,需要先安装PostgreSQL数据库,并配置库的头文件和链接库。
1.使用Homebrew(Package manager for macOS)安装PostgreSQL
brew install postgresql
2.将PostgreSQL安装目录下include文件目录添加至头文件搜索路径
-I/usr/local/Cellar/postgresql/13.3_3/include
3.将PostgreSQL安装目录下lib文件目录添加至链接库搜索路径
-L/usr/local/Cellar/postgresql/13.3_3/lib -lpq
#include <iostream>
#include <pqxx/pqxx>
int main()
{
std::string user = "username";
std::string password = "password";
std::string host = "localhost";
std::string port = "5432";
std::string database_name = "dbname";
std::string connection_string = "postgresql://" + user + ":" + password + "@" + host + ":" + port + "/" + database_name;
pqxx::connection conn(connection_string);
if (conn.is_open())
{
std::cout << "Opened database successfully: " << conn.dbname() << std::endl;
}
else
{
std::cout << "Can't open database" << std::endl;
return 1;
}
conn.disconnect();
return 0;
}
连接数据库的API使用pqxx::connection
类。调用类的is_open
方法可判断是否连接成功。
#include <iostream>
#include <pqxx/pqxx>
int main()
{
std::string user = "username";
std::string password = "password";
std::string host = "localhost";
std::string port = "5432";
std::string database_name = "dbname";
std::string connection_string = "postgresql://" + user + ":" + password + "@" + host + ":" + port + "/" + database_name;
pqxx::connection conn(connection_string);
if (conn.is_open())
{
pqxx::work txn{conn};
std::string sql = "INSERT INTO mytable VALUES (1, 'value1');";
txn.exec(sql);
std::cout << "Query executed successfully!" << std::endl;
txn.commit();
}
else
{
std::cout << "Can't open database" << std::endl;
return 1;
}
conn.disconnect();
return 0;
}
执行SQL语句使用的API是pqxx::work
类。该类将SQL语句绑定到在事务中执行该语句的工作区。调用commit
方法提交事务。
#include <iostream>
#include <pqxx/pqxx>
int main()
{
std::string user = "username";
std::string password = "password";
std::string host = "localhost";
std::string port = "5432";
std::string database_name = "dbname";
std::string connection_string = "postgresql://" + user + ":" + password + "@" + host + ":" + port + "/" + database_name;
pqxx::connection conn(connection_string);
if (conn.is_open())
{
pqxx::work txn{conn};
std::string sql = "SELECT * FROM mytable;";
pqxx::result r = txn.exec(sql);
for (auto row : r)
{
std::cout << "id = " << row[0].as<int>() << ", value = " << row[1].as<std::string>() << std::endl;
}
txn.commit();
}
else
{
std::cout << "Can't open database" << std::endl;
return 1;
}
conn.disconnect();
return 0;
}
查询数据库使用的API是pqxx::result
类。该类包含了查询结果中的所有行。需调用as
方法进行类型转换。
PostgreSQL-C C++接口是一个十分强大的工具,有助于C++程序员加速数据库开发,并在程序性能和数据库性能方面有很好的表现。同时该接口库具有跨平台和开源的特点,可以满足各式各样的应用需求。