Tell me why when you try to use the function, the Error goes out: can't execute INSERT-query? What is wrong with the request?

Table structure

1 id int(11) 2 time datetime 3 rad int(11) 4 temp float 5 hum float 6 pres int(6) 

Code

 void insertToDb(short int r, float t, float h, short int p) { MYSQL conn; if(!mysql_init(&conn)) { fprintf(stderr, "Error: can't create MySQL-descriptor\n"); exit(1); } if(!mysql_real_connect(&conn, "localhost", "user", "xxxxx", "my_db", 0, NULL, 0)) { fprintf(stderr, "Error: %s\n", mysql_error(&conn)); exit(1); } if(mysql_query(&conn, "SET NAMES 'utf8' COLLATE 'utf8_general_ci'") != 0) { fprintf(stderr, "Error: can't set character set\n"); exit(1); } char query[400]; sprintf(query, "INSERT INTO my_table(rad, temp, hum, pres) VALUES (%i, %f, %f, %i)", r, t, h, p); if(mysql_query(&conn,query) !=0); { fprintf(stderr, "Error: can't execute INSERT-query\n"); exit(1); } mysql_close(&conn); } 
  • Please output the error message with mysql_error () and complete the response. - cheops
  • Thanks for the advice!) The case turned out to be no autoincrement id .. - lavAzza

1 answer 1

You have specified the tags and the header of the C++ question, but use the library written in C I recommend that you go first to https://github.com/mysql/mysql-connector-cpp or any equivalent you like.

 sprintf(query, "INSERT INTO my_table(rad, temp, hum, pres) VALUES ('%i','%f','%f','%i')", r, t, h, p); 

For this use SqlStatement con->prepareStatement .

And Binding Parameters and for error control use

 try { ....code } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "(" << EXAMPLE_FUNCTION << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } 

See more examples here .

Successful development!

  • The fact is that I have no idea with or with ++, sorry for illiteracy.) The file extension was cpp, so I assumed. In general, the problem was in id autoincrement. Thanks for trying to help! - lavAzza
  • one
    @ user3843377 - the problem with this code is that the request is compiled by concatenation. This opens the way for hackers and SQL injections. - gbg