我正在使用 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();
}