How to do a sql_query with a variable in C++?

-1

I'm trying to get different values from my database dynamically so i need to put a variable in my mysql_query.

#include <cstdlib>
#include <iostream>
#include <mysql.h>
#include <string>
#include <sstream>

using namespace std;

MYSQL* ConnexionSql()
{
    MYSQL* conn;
    conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "ADAI1819", "projetADAI", 3306, NULL, 0);
    return conn;
}

int NbCompo() //Without any variable this work perfectly
{
    MYSQL* conn = ConnexionSql();
    MYSQL_RES *res_set;
    MYSQL_ROW row;
    mysql_query(conn, "select NbCompo from Envoi");
    res_set = mysql_store_result(conn);
    row = mysql_fetch_row(res_set);
    string chaine = row[0];
    int result = std::stoi(chaine);
    return result;
}

int NbProduit(string x) //And here is my problem
{
    MYSQL* conn = ConnexionSql();
    MYSQL_RES *res_set;
    MYSQL_ROW row;

    x = "Select " + x + " from Envoi";
    mysql_query(conn, x.c_str());
    res_set = mysql_store_result(conn);
    row = mysql_fetch_row(res_set);
    string chaine = row[0];
    int result = std::stoi(chaine);
    return result;
}

It Build perfectly but when i run it i get this message "Exception thrown at 0x00007FFFF7C1BD66 (libmysql.dll) in ProjectADAI.exe: 0xC0000005: Access Violation while reading location 0x0000000000000010." (it's a translation i'm french excuse my english).

c++
mysql
visual-studio
asked on Stack Overflow Mar 27, 2019 by Hugo Saunier

1 Answer

0

mysql_real_connect is probably returning null. You need to check whether the result is null then call mysql_error to discover the error code.

answered on Stack Overflow Apr 1, 2019 by Alan Birtles

User contributions licensed under CC BY-SA 3.0