我使用 PostgreSQL 的 libpqxx C++ 客户端 API 作为 cockroachDB 上的驱动程序。来自 cockroachDB 文档:
pqxx::connection c("postgresql://maxroach@localhost:26257/bank")
这需要用户和数据库作为前提。是否有任何 C++ API 可以将其分为以下两个步骤?
1) First connect just with user.
2) create data base.
我尝试了下面的代码,但它失败了,因为它需要root用户 特权。
void roachDB::createDB(const string &dbName)
{
pqxx::nontransaction w(roachDBconn);
w.exec("CREATE DATABASE " + dbName);
w.commit();
}
感谢您的帮助!
======= Edit 1 : Working code based on @clemens tip ===========
void roachDB::createDB(const string &dbName, const string &user)
{
pqxx::connection c("postgresql://root@localhost:26257/template1");
pqxx::nontransaction w(c);
try {
w.exec("CREATE DATABASE " + dbName);
} catch (pqxx::sql_error &e) {
string sqlErrCode = e.sqlstate();
if (sqlErrCode == "42P04") { // catch duplicate_database
cout << "Database: " << dbName << " exists, proceeding further\n";
c.disconnect();
return;
}
std::cerr << "Database error: " << e.what()
<< ", error code: " << e.sqlstate()
<< "SQL Query was: " << e.query() << "\n";
abort();
}
w.exec("GRANT ALL ON DATABASE " + dbName + " TO " + user);
w.commit();
c.disconnect();
}
最佳答案
如果不指定数据库,则无法连接到 Postgres 服务器。但总有一个数据库template1
可供您用于您的目的。因此,连接
pqxx::connection c("postgresql://maxroach@localhost:26257/template1")
并使用该连接创建新数据库。
您还应该授予 maxroach
创建数据库的权限:
GRANT CREATE DATABASE TO maxroach;
但这必须由具有 super 用户权限的数据库用户执行(例如 postgres
)。
关于postgresql - libbqxx C++ API 无需数据库名称即可连接到 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122358/