Home > database >  I am creating a SQL Handler in a function, how do I pass it to other functions?
I am creating a SQL Handler in a function, how do I pass it to other functions?

Time:10-19

I am creating a function in order to connect to MYSQL database and I want it to remain open so that I can later call a function QuerySQL() to get data and process it, however, when I try to pass the handler of the SQL connection, it stops working. I think it is only assigning the value in the local function and when it exits the function the value of conn is lost but I dont know how to fix it.

Thanks for the help.

#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>  
#include <mysql.h>

//Declaracion de funciones

//Funcion para crear una conexion con el servidor SQL
void ConnectToSQL(char respuesta_sql[300],MYSQL *conn)
{
    //parametros para inicializar la conexion
    char *server = "localhost";//servidor
    char *user = "root";//usuario
    char *password = "mysql";//contrasena
    char *database = "ProyectoSO";//base de datos que usremos
    //Creamos una conexion al servidor MYSQL 
    conn = mysql_init(NULL);
    if (conn==NULL) {
        sprintf(respuesta_sql,"Error al crear la conexion: %u %s", mysql_errno(conn), mysql_error(conn));
    }
    /* Inicializar la base de datos */
    conn = mysql_real_connect (conn, server,user, password, database,0, NULL, 0);
    if (conn==NULL) {
        sprintf (respuesta_sql,"Error al inicializar la conexion: %u %s", mysql_errno(conn), mysql_error(conn));
    }
    else
    {
        sprintf (respuesta_sql,"Exito");
    }
}
//Funcion para desconectar de SQL
void DisconnectFromSQL(char respuesta_sql[300],MYSQL *conn)
{
    MYSQL *ptr = conn;
    mysql_close(conn);
    sprintf(respuesta_sql,"Desconectado");
}


//Funcion para hacer consultas
int QuerySQL(char consulta[300], MYSQL *conn, MYSQL_ROW *row)
{
    MYSQL_RES *resultado;
    int err;
    int resultado_consulta;
    
    err = mysql_query(conn, consulta);
    if (err!=0 && err!=1) 
    {
        resultado_consulta = -1;//Error al consultar la base de datos
        exit (1);
    }
    else if(err==0)
    {
        //recogemos el resultado de la consulta
        if (resultado != NULL)
        {
            resultado = mysql_store_result(conn);
            *row = mysql_fetch_row(resultado);
        }
        resultado_consulta=0;
    }
    return resultado_consulta;
}
int main(int argc, char *argv[]) 
{
    MYSQL conn;//Se crea el conector
    MYSQL *ptrconn = &conn;
    char respuesta_sql[300];//Aqui se reciben los errores del servidor sql
        
    ConnectToSQL(respuesta_sql,&conn);
    printf("%s",respuesta_sql);
    
    DisconnectFromSQL(respuesta_sql,&conn);
    return 0;
}

CodePudding user response:

Consider returning MYSQL object rather than passing as argument when creating. This provides a pointer to the the object that can be tested for success by the caller before using, and can then be easily passed from one function to another, then used to close the connection when no longer needed.

Example prototype and usage:

MYSQL * ConnectToSQL(char respuesta_sql[300])
{
    ...
    MYSQL *conn = mysql_init(NULL);
    ...
    return conn;
    ...

In main()

...
char respuesta_sql[300]={0};
char consulta[300]={0};
MYSQL_ROW row=0;
MYSQL *conn = ConnectToSQL(respuesta_sql);
if(conn)
{
     //use conn
     int ret = int QuerySQL(consulta, conn, &row);
     ...
     DisconnectFromSQL(conn);
}
...
  • Related