c - 尝试从 C 连接到 postgres 时出现问题

标签 c postgresql libpq

我正在尝试使用 C 中的 libpq 创建数据库连接。如果我使用 PQconnectdb 创建该连接,一切正常,但如果我使用 PQconnectdbParams 函数创建它,则仅使用以不同方式存储的相同参数(请参阅 libpq reference ),我收到段错误错误,没有任何其他消息。有人可以帮我解决这个问题吗?

你可以在下面看到我的代码:


int main(int argc, char *argv[]) {
        char **keywords;
        char **values;
        char *line = malloc(50);
        char *prop, *tmp, *val;
        int i = 0, j = 0;
        FILE *creds = fopen("/path/to/file.props", "r");
        if (creds == NULL) {
           LOG("%s", "error: cannot open credentials file.\n");
           exit(1);
        }

        keywords = malloc(5 * sizeof(*keywords));
        values = malloc(5 * sizeof(*values));
        while (fgets(line, LINE_SIZE, creds) != NULL) {
                if (line[strlen(line) - 1] == '\n')
                        line[strlen(line) - 1] = '\0';
                prop = line;
                while(*(prop++) != '=') {
                        i++;
                }
                tmp = prop;
                prop = malloc(i + 1);
                strncpy(prop, line, i);
                prop[i] = '\0';
                keywords[j] = prop;
                val = malloc(strlen(line) - strlen(prop) + 1);
                strcpy(val, tmp);
                values[j++] = val;
                i = 0;
        }
printf("%s %s %s %s %s\n", keywords[0], keywords[1], keywords[2], keywords[3], keywords[4]); //that lines prints ok
printf("%s %s %s %s %s\n", values[0], values[1], values[2], values[3], values[4]); //
        PGconn *conn = PQconnectdbParams(keywords, values, 0);

        if (PQstatus(conn) != CONNECTION_OK) {

                fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
                PQfinish(conn);
                exit(1);

        }
}

最佳答案

PQconnectdbParams 的文档说:

This function opens a new database connection using the parameters taken from two NULL-terminated arrays.

但在您的代码中,keywordsvalues 数组不是以 NULL 结尾。 它为 5 个参数分配 5 个指针,但它应该为 5 个参数分配 6 个指针加上一个 NULL 指针。

关于c - 尝试从 C 连接到 postgres 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15039237/

相关文章:

c - 列出C程序中的多个接口(interface)

在 C 中将整数值转换为 char?

Python/Psycopg2/PostgreSQL Copy_From 循环在进行时变慢

php - 用于 facebook/heroku 的 AS3 postgresql 和 amfphp?

c++ - PostgreSQL不支持嵌套的BEGIN和END语句,即使它不支持自主事务?

c - 在 10 年的跨度和 1 秒的分辨率下,什么时间戳具有最佳的空间效率?

c - 如何有效地在文件中写入大量 NULL 字节序列?

java - 在 Spring Boot 中存储和检索密码以形成服务器连接

c++ - 我应该如何处理 libpq for postgresql 中的错误

cmake - FindPostgreSQL.cmake 无法在 ubuntu 上运行