title: libbqxx C++ API to connect to PostgreSQL without DB name
body: <p>I am using libpqxx C++ client API for PostgreSQL as the driver on cockroachDB. From cockroachDB doc:</p>
  
  <pre><code>pqxx::connection c("postgresql://maxroach@localhost:26257/bank")
  </code></pre>
  
  <p>This requires user and database as precondition. Are there any C++ APIs to separate this into two steps as below ?</p>
  
  <pre><code>1) First connect just with user.
  2) create data base.
  </code></pre>
  
  <p>I have tried the below code, but it failed as it needs root user
  privileges.</p>
  
  <pre><code>void roachDB::createDB(const string &amp;dbName)
  {
      pqxx::nontransaction w(roachDBconn);
      w.exec("CREATE DATABASE " + dbName);
      w.commit();
  }
  </code></pre>
  
  <p>Thanks for your help!</p>
  
  <pre><code>======= Edit 1 : Working code based on @clemens tip ===========
  
  void roachDB::createDB(const string &amp;dbName, const string &amp;user)
  {
      pqxx::connection c("postgresql://root@localhost:26257/template1");
      pqxx::nontransaction w(c);
      try {
          w.exec("CREATE DATABASE " + dbName);
      } catch (pqxx::sql_error &amp;e) {
          string sqlErrCode = e.sqlstate();
          if (sqlErrCode == "42P04") { // catch duplicate_database
              cout &lt;&lt; "Database: " &lt;&lt; dbName &lt;&lt; " exists, proceeding further\n";
              c.disconnect();
              return;
          }
          std::cerr &lt;&lt; "Database error: " &lt;&lt; e.what()
              &lt;&lt; ", error code: " &lt;&lt; e.sqlstate()
              &lt;&lt; "SQL Query was: " &lt;&lt; e.query() &lt;&lt; "\n";
          abort();
      }
      w.exec("GRANT ALL ON DATABASE " + dbName + " TO " + user);
      w.commit();
      c.disconnect();
  }
  </code></pre>