Search code examples
c++mysqlpostgresqlsoci

Why I have not enough privilege to database when I use soci to connect to postgresql?


I can correctly use soci to connect to mysql and execute sql. But the same way to postgresql does not work. this is my makefile and main.cpp:

    all: main.cpp
    g++ -Wall -g -o main main.cpp  -lpq -lsoci_core -lsoci_postgresql -ldl
clean:

And this is main.cpp:

#include <soci/soci.h>
#include <soci/postgresql/soci-postgresql.h>
#include<iostream>
#include<istream>
#include<ostream>
#include<string>
#include<exception>

using namespace std;
using namespace soci;

int main() {
    try {
        session sql("postgresql://dbname=mydb_0");
        int count ;
        sql<< "select count(*) from student", into(count);
        cout<<"count="<<count<<endl;
    } catch (exception const &e) {
        cerr<<"Error:" <<e.what()<<endl;
    }
}

This is the error output:

Error:Cannot execute query. Fatal error. 错误:  对关系 student 权限不够
 while executing "select count(*) from student".

I can execute sql "select count(*) from student"in terminal but the C++ code dose not work, Why?


Solution

  • Ok, I have solved this problem by myself. Unlike other example, I add "host=127.0.0.1" and "port=5432" to the init statement.It is like this :session sql(postgresql, "host=127.0.0.1 dbname=exampledb user=postgres password=123 port=5432");. I hope this solution would help others.