c++mysql++

How to fix 'error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]' in C++?


I try to connect mysql and c++. This is the process of trying to put the entered value into the DB. An error occurs when g++ compiling.

I'm coding using c++98 in visual studio 2017 and CentOS7. The Mysql Connector used is Mysql++ ver.8.0.

#include "[~ PATH]/mysql++/include/mysql++/cmdline.h"
#include "[~ PATH]/mysql++/include/mysql++/mysql++.h"
#include "[~ PATH]/mysql++/examples/printdata.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
{
        char buffer[256];
        string name;
        string id;
        string password;
        string department;

        cout << ">> Sign Up <<\n" << endl;
        cout << "1.Name: "; cin >> name;
        cout << "2.ID: "; cin >> id;
        cout << "3.PASSWORD: "; cin >> pw;
        cout << "4.Department: "; cin >> dpt;

        mysqlpp::Connection conn(false);
        if (conn.connect("member_list", "localhost", "user", "password1234"))
        {
                **mysqlpp::Query query 
                 = conn.query(sprintf(buffer,"INSERT INTO signup_member (name,id,password,department) 
                   VALUES ('%s','%s','%s','%s')",name.c_str(),id.c_str(),password.c_str(),department.c_str()));**
                if (mysqlpp::StoreQueryResult res = query.store()) {
                        cout << "Sign up SUCCESS!" << endl;
                }
                else {
                        cerr << "Sign up FAIL. Try again." << '\n' << query.error() << endl;
                        return 1;
                }
                return 0;
        }
        else {
                cerr << "DB connection failed: " << conn.error() << endl;
        }
}

When I searched, it said to save the value in the buffer using 'sprintf' and then to save it in the DB. I expect it works well, but it's not. sign_up.cpp:30:175: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]


Solution

  • sprintf return an int which represents

    On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string. On failure, a negative number is returned.

    & not the char array you wrote your data in as you are expecting so basically you should do :

    sprintf(buffer,"INSERT INTO signup_member (name,id,password,department) 
                       VALUES ('%s','%s','%s','%s')",name.c_str(),id.c_str(),password.c_str(),department.c_str());
    mysqlpp::Query query 
                     = conn.query(buffer);