0

I have two problems with the MySQL C API. How do I get variable to be added to the table when I do the mysql_query() and how do I get the table show decimals?

Here is my code:

void insertDataToTable(MYSQL* con, float temp, int k)
{
    mysql_query(con, "INSERT INTO Weatherstation VALUES(@k,'Temperature:', @temp)");
}

Thank you!

4
  • 2
    To send variables to the MySQL server, you should use the prepared statement API (sure, you could concatenate a string representation of its value into your SQL command—but that gives rise to the possibility of SQL injection, buggy escaping and a needless waste of resources). It's not clear what you mean by "get the table show decimals", please elaborate? Commented Sep 11, 2015 at 10:43
  • I send a floating point value to the Weatherstation table like this: mysql_query(con, "INSERT INTO Weatherstation VALUES(1, 'Temperature:', 124.3)"); But when I logged into the database and checked that value from the table it showed just 124 without the decimal part. Commented Sep 11, 2015 at 11:09
  • What is the data type of the relevant column? Commented Sep 11, 2015 at 11:14
  • Oh yes of course, there is the problem! I have specified it as an integer. Thank you! Commented Sep 11, 2015 at 11:20

2 Answers 2

2

Try this

void insertDataToTable(MYSQL* con, float temp, int k)
{
    char query[255] ;

    sprintf( query, "INSERT INTO Weatherstation VALUES(%ld,'Temperature:', %d)", temp, k );
    mysql_query(con, query );


}
Sign up to request clarification or add additional context in comments.

Comments

0

MySQL does not support host variables that well, the previous answer shows the correct approach in building the query into a string and then using mysql_query(someconnection, string).

What is absolutely shocking is that this is not documented as much as it should be. When I had to learn this I had 30 years of DB2 and C, and I had to get this from GitHub after 2 hours of fruitless searching for "MySQL Host Variables".

You should also be aware of mysql_real_query if your query is not a conventional string and contains embedded nulls, it is passed the length of the string, but can also move a strlen() call off the server.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.