-1

I am using JSON format to save data in my c++ program , i want to send it to MySql database (the table tab has one column with type : TEXT) but the query failed (tested also VARCHAR and CHAR )

this is a part of the code since we are not interrested in the rest

     string json_example = "{\"array\":[\"item1\",\"item2\"], \"not an array\": \"asdf\"}";
   mysql_init(&mysql);  //initialize database connection
   string player="INSERT INTO tab values (\"";
    player+= json_example; 
    player += "\")"; 
    connection = mysql_real_connect(&mysql,HOST,USER,PASSWD,DB,0,NULL,0); 
// save data to database
   query_state=mysql_query(connection, player.c_str());  // use player.c_str()

to show the final query that will be used : cout << player gives :

INSERT INTO tab values ("{"array":["item1","item2"], "not an array": "asdf"}")

using for example string json_example = "some text"; is working but with the json format it is not working , maybe the problem came from the use of curly bracket {} or double quotes "" but i haven't find a way to solve it .

i'm using : mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu (armv7l) under raspberry pi 2

Any help will be appreciated , thanks .

The Beast
  • 1,629
  • 2
  • 29
  • 42
  • 1
    You may need to escape your quotes like: `json_example = "{\\\"array...` because the SQL uses quotes. You'd need a triple escape `\\\\`, 2 for the backslash `\\` and one for the quote. – Galik Aug 12 '15 at 15:11
  • @Galik you solution worked fine for me , thanks .... however i think that the method i use is not the correct way to use JSON with MySql do you ? – The Beast Aug 12 '15 at 15:28
  • 1
    @user3530803: What's correct and what not depends on your requirements. Personally, I think it's a horrible idea to store JSON in a database, but then again, I am biased against JSON in general. I have never encountered a situation in which storing unstructured data was preferred over storing structured one, and SQL is an extremely powerful language to define structured data. – Christian Hackl Aug 12 '15 at 15:36
  • @ChristianHackl yes i agree , so JSON could be used to store data and retreive them from a file for example not with databases – The Beast Aug 12 '15 at 16:12
  • @user3530803: The ability to use text files for storage is one of the reasons you might have chosen JSON in the first place. Storing the JSON in a database defeats this purpose. – Christian Hackl Aug 12 '15 at 17:08

1 Answers1

4

Use a prepared statement. See prepared statements documentation in the MySQL reference manual.

Prepared statements are more correct, safer, possibly faster, and keep your code cleaner. You get all those benefits and don't need to escape anything. There is hardly a reason not to use them.


Something like this might work. But take it with a grain of salt, because I have not tested or compiled it. It should just give you the general idea:

MYSQL_STMT* const statement = mysql_stmt_init(&mysql);
std::string const query = "INSERT INTO tab values(?)";
mysql_stmt_prepare(statement, query, query.size());
MYSQL_BIND bind[1] = {};
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = json_example.c_str();
bind[0].buffer_length = json_example.size();
mysql_stmt_bind_param(statement, bind);
mysql_stmt_execute(statement);
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • this magic wich i have never heard about is working :) thanks for adding the code , i have just copy & paste it and compiled by `g++ -I/usr/include/mysql -std=c++0x -o outf jsonToMySql.cpp \`mysql_config --cflags --libs\` ` – The Beast Aug 12 '15 at 17:08
  • 1
    @user3530803: Once you get used to prepared statements, you will never again want to use string concatenation to build queries :) Note that prepared statements are also your first line of defense against SQL injections. – Christian Hackl Aug 12 '15 at 17:09
  • please why you have added "?" in the query .... i heard also about MySql connector ... wich one is better ? – The Beast Aug 12 '15 at 17:14
  • @user3530803: The `?` means *"insert the parameter here"*. I am not familiar with MySQL connector, sorry. Even if I was familiar with it, "better" is always relative. In any case, knowledge of prepared statements is a must for a professional database programmer. – Christian Hackl Aug 12 '15 at 17:18
  • 1
    @user3530803: I'd like to add that this is fundamentally different to using `+` to concatenate strings. Your original code sent a complete, fixed query to the database. With prepared statements, you supply more logic and let the database itself insert the parameter **after** the query has been parsed. So whatever is in your parameter does not affect parsing. – Christian Hackl Aug 12 '15 at 17:20