Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql++ insert how to?

Tags:

c++

mysql++

I am having problem to INSERT some values into database. Database name is users, and table is heroes. I am doing some mmorpg game developing for purpose of learning.

This is mysql code that works

INSERT INTO heroes (HeroID,Strenght, Dexterity, Vitality, Wisdom, Inteligence, Luck, Name, Level, XP) VALUES (NULL,  17, 13, 17, 15, 9, 8, 'works', 4, 3750);

But when I try that from c++ via mysql++ I get error.

Code:

#include <mysql++/mysql++.h>

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
// Connect to the database.
mysqlpp::Connection conn(false);

if (conn.connect("users", "localhost",
        "root", "toor")) 
{

    mysqlpp::Query query = conn.query();
   query << "INSERT INTO heroes" <<
    "VALUES (NULL, 17, 13, 17, 15, 9, 8, doSomething,3, 3260);";

    query.execute();
    if (mysqlpp::StoreQueryResult res = query.store()) 
    {
     // nothing to do here
    }

    else 
    {
        cerr << "Failed to get item list: " << query.error() << endl;
        return 2;
    }

    return 0;
}

   else 
    {
    cerr << "DB connection failed: " << conn.error() << endl;
    return 1;
    }
}

Error I get is: Failed to get item list; You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL, 17, 13, 17, 15, 9, 8, doSOmething,3, 3260)' at line 1

p.s. I am sending NULL becouse that field is auto-increment (using for ID) I tried almost all possible alternatives like adding '', separataning and whatnot. Can somebody help me with this line of code, since I can't find ang good tutorial that helps on this matter.

Thanks in advance

like image 558
user2597689 Avatar asked Feb 27 '14 17:02

user2597689


2 Answers

Have you tried to add an space in your string?

query << "INSERT INTO heroes " <<
    "VALUES (NULL, 17, 13, 17, 15, 9, 8, 'doSomething', 3, 3260);";

Also, as pointed out by hmjd, doSomething needs to be quoted, like 'doSomething'.

like image 189
Natan Streppel Avatar answered Sep 28 '22 06:09

Natan Streppel


The string doSomething needs quoted:

query << "INSERT INTO heroes "
      << "VALUES (NULL, 17, 13, 17, 15, 9, 8, 'doSomething', 3, 3260);";

and as pointed out by Streppel a space is required between heroes and VALUES.

like image 36
hmjd Avatar answered Sep 28 '22 05:09

hmjd