2013-12-12 45 views
0

我正在使用C程序与Postgres数据库交谈。PostgreSQL&C:如何打印整个PostgreSQL结果

我想创建一个方法,允许用户在C程序中键入一个自定义查询,并查看Postgres打印在其命令行客户端psql中打印的结果。

对于其他查询,我能够使用我在文档中找到的函数。麻烦的是,这些只是工作,因为我知道我需要的列数和相应的头文件等

例如:

void* executeCustomQuery(const char* query){ 
    PGresult* res = PQexec(conn, query); 
    //print all entries 
    printf(PRODUCTS_TABLE_HEADER); 
    int i; 
    for (i = 0; i < PQntuples(res); i++){ 
     printf("| %s | %s | %s |", PQgetvalue(res, i, 0), PQgetvalue(res, i, 1), PQgetvalue(res, i, 2)); 
    } 
    PQclear(res); 
} 

我不能使用这个代码,如果我不知道是什么我回来了。

有没有人知道有任何方式可以打印出Postgres的直接结果?

+0

Postgres的一个很好的“特性”是它的免费/开放源代码软件 - 查看'psql'代码。 –

+0

RTFM。一切都在那里:http://www.postgresql.org/docs/9.2/static/libpq-exec.html#LIBPQ-EXEC-SELECT-INFO –

+2

我发现后不久发现。 “RTM”虽然可以做到,但不需要那个“F” – CodyBugstein

回答

1

我最终找到了方法PQfname(),它给了我表的列名称。 使用这个我可以用一些for循环重建表格。这不是我所期待的,但值得一提。

PGresult* res = PQexec(conn, query); 
    char headerPrint[500]; 
     strcpy(headerPrint, "|"); 
     int h; 
     for (h = 0; h < PQnfields(res); h++){ 
       strcat(headerPrint, " "); 
       strcat(headerPrint, PQfname(res, h)); 
       strcat(headerPrint, " |"); 
       if (h == PQnfields(res)-1){ 
        strcat(headerPrint, "\n"); 
       } 
     } 
     printf("%s", headerPrint); 
     //Print content 
     int i; 
     char resultPrint[500]; 
     strcpy(resultPrint, "|"); 
     for (i = 0; i < PQntuples(res); i++){ 
      int j; 
      for (j = 0; j < PQnfields(res); j++){ 
       strcat(resultPrint, " "); 
       strcat(resultPrint, PQgetvalue(res, i, j)); 
       strcat(resultPrint, " |"); 
       //printf("%s %d %s", "Value of i is: ", i, "\n"); 
       //printf("%s %d %s", "Value of j is: ", j, "\n"); 
       //New line at the end 
       if (j == PQnfields(res)-1){ 
        strcat(resultPrint, "\n"); 
       } 
      } 
      printf("%s", resultPrint); 
      strcpy(resultPrint, "|"); //Clear the current row and start over 
     } 
     PQclear(res); 
+0

读者还应该看看'PQprint'。 –