我将PostgreSQL的libpqxx C ++客户端API用作cockroachDB上的驱动程序。来自cockroachDB doc:
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();
}
答案 0 :(得分:1)
如果不指定数据库,则无法连接到Postgres服务器。但是总有数据库template1
可以用于您的目的。所以,连接
pqxx::connection c("postgresql://maxroach@localhost:26257/template1")
并使用该连接创建新数据库。
您还应该授予maxroach
使用以下内容创建数据库的权限:
GRANT CREATE DATABASE TO maxroach;
但这必须由具有超级用户权限的数据库用户执行(例如postgres
)。