简体   繁体   中英

Can't connect to database in c

I have a code that contains some functions unrelated to database. when I added functions for connecting to database, the code occurs Segmentation fault (core dumped) . but when I use those functions (connecting to db) in an isolated file there is no problem.

#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>

void exit_db(PGconn *connection){
        //this function close the connection
        //between progrem and database.
        PQfinish(connection);
}

void make_connection(PGconn *connection){
        //this function stablish a connection 
        //between program and database.
        connection = PQconnectdb("user=user "\
                                "password=123 "\
                                "dbname=project_db");
        if(PQstatus(connection) == CONNECTION_BAD){
                printf("%s\n", PQerrorMessage(connection));
                exit_db(connection);
        }
}

void create_table_fp_stores_data(PGresult *re, PGconn *connection){
        //this function create fp_stores_data table if does not exist.
        re = PQexec(connection ,"CREATE TABLE IF NOT EXISTS fp_stores_data_test (time TIME,"\
                                                        "province VARCHAR(20), city VARCHAR(20),"\
                                                        "market_id INTEGER );");
                if(PQresultStatus(re)==PGRES_COMMAND_OK){
                        printf("table created!\n");
                }else{
                        printf("%s\n", PQresultErrorMessage(re));
                        printf("%s\n", PQerrorMessage(connection));
                }
        PQclear(re);
}

int main(){
    PGconn *con;
    PGresult *res;
    make_connection(con);
    create_table_fp_stores_data(res, con);
    return 0;
}

this code has no problem but when I add some unrelated functions to this, it occurs problem.I can put my whole code here but I'm trying to avoid congestion.

The problem is in the definition of

void make_connection(PGconn *connection)

The PGconn * is passed by value, so connection inside the function body is a different variable than con in your main function.

You assign to connection in make_connection , but that doesn't change the value of con .

There are two solutions:

  1. Pass the address of con :

     void make_connection(PGconn **connection) { *connection = PQconnectdb(...); } make_connection(&con);
  2. (better) have the function return the pointer:

     PGconn *make_connection() { PGconn *result; result = PQconnectdb(...); return result; } con = make_connection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM