2

I have such program which works from "C" OK. Creates a table if they dont exists.

PGresult *result;
conn = PG_connect();
if (conn)
{
    if (!PG_begin(conn))
    {
        char strtable[512] = {0};
        sprintf(strtable, "%s", "CREATE TABLE IF NOT EXISTS mytable");
        strcat(strtable, " (setting TEXT, value TEXT, rez1 TEXT, rez2 TEXT)");
        result = PQexec(conn, strtable);
        if (PQresultStatus(result) != PGRES_COMMAND_OK)
        {
            printf("CREATE TABLE failed: %s\n", PQerrorMessage(conn));
            PQclear(result);
            exit_nicely(conn);
        }

        PQclear(result);
        PG_end(conn);
    }
}
PQfinish(conn);

That mean I am connected properly.
But for why (on earth) in the same code and situation this query don't work?

sprintf(strtable, "%s%s", "SELECT 1 FROM pg_tables WHERE tablename=", "\'invli\'");

I allways get PQresultStatus(result) = 2 and PQerrorMessage(conn) without any text!

All of that I uses from npgsql without problems. Additional question, how is best to get relsults from such simple queries, or "COUNT" which have only one information? In npgsql I uses "ExecuteScalar" function.

1 Answer 1

4

According to postgresql header file, status code 2 is PGRES_TUPLES_OK which means "a query command that returns tuples was executed properly by the backend, PGresult contains the result tuples". So no error here. On the contrary, returning PGRES_COMMAND_OK for a SELECT query would be strange.

See also status codes in documentation (http://www.postgresql.org/docs/current/static/libpq-exec.html):

PGRES_COMMAND_OK Successful completion of a command returning no data.

PGRES_TUPLES_OK Successful completion of a command returning data (such as a SELECT or SHOW).

Sign up to request clarification or add additional context in comments.

2 Comments

Sounds logical, thank you. Pitty, for that I lost almost all the day! And for read simple values from query result?
I am not aware of a single libpq function that retrieves a scalar value from query result. But I suppose reading the value via traditional multi-tuple interface won't be a big performance problem (anyway, a query to a database takes much more time than parsing a single-row result and locating fields even if the fields are addressed by names instead of indexes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.