pyCthon
pyCthon

Reputation: 12361

mysql connector errors with conversion of code from java to c++

I have a java code that works

//**Correct Java query**
    QueryString = "INSERT IGNORE INTO stock_prices (symbol,timestamp,open,high,low,close,vol) VALUES ('"
      + data[0] + "', '" + data[1] + "', " + data[2] + ", " + data[3] + ", " + data[4] + ", "
      + data[5] + ", " + data[6] + ")";

However in java you can add double or int with string easily and in c++ you cannot, i've tried multiple things for the query in C++ but it isn't working like i think it should. What am I doing wrong? Is there a better way in C++ to do this. Heres my query.

//***Incorrect C++ query**
 sql::Statement *stmt;
 stmt = con->createStatement();

for (int i = 0; i < (int)timestamp.size(); i++) {
  string s = symbols[ii];
  string t = timestamp[i];
  double v = vwap[i]; 

string query = "INSERT INTO stock_prices(symbol,time_stamp,vwap) VALUES('" + s + "', '" + t + "', " + boost::lexical_cast<std::string>(v) + ")";
 stmt->executeQuery(query);
}

The above code runs for 1 iteration of the for loop and then the following error is thrown

 terminate called after throwing an instance of 'sql::SQLException'
  what():  
Aborted

I printed out the C++ query(which works if i copy paste it into mysql)

INSERT INTO stock_prices(symbol,time_stamp,vwap) VALUES('A', '2010-01-04 08:01:00', 0)

Upvotes: 1

Views: 365

Answers (2)

dreamcrash
dreamcrash

Reputation: 51483

Shouldn't you be using ' (single quote) on the remaining elements ?

QueryString = "INSERT IGNORE INTO stock_prices
(symbol,timestamp,open,high,low,close,vol) VALUES 
       ('"
       + data[0] + "', '" + data[1] + "', '" 
       + data[2] + "', '" + data[3] + "', '" 
       + data[4] + "', '" + data[5] + "', '" 
       + data[6] + "'
       )";

Instead of this:

string s = "blah";
string t = "bla";
double v = 43;    

string query = "INSERT INTO stock_prices(symbol,time_stamp,vwap) VALUES('" + s + "', '" + t + "', " + boost::lexical_cast<std::string>(v) + ")";

try this:

double v = 43.0;
char vs[20];
sprintf(vs,"%f",v);

string query = "INSERT INTO stock_prices(symbol,time_stamp,vwap) VALUES('" + s + "', '" + t + "', " + vs + ")";

Upvotes: 1

nicephotog
nicephotog

Reputation: 11

No, try using header string.h

char query[1024]; /* you get 1024 chars to try it */
char qstart="INSERT INTO stock_price_(symbol,timestamp,vol) VALUES(";
char qstr2="whatever s is ";
char separator=",";
char leftelips="(";
char rightelips=")";

strcpy(query,qstart);
strcat(query,qstr2); 
strcat(query,separator);
/* ...........  e.t.c.  */

Upvotes: 1

Related Questions