mysql and c — use variable in query

孤者浪人 提交于 2019-12-13 07:40:16

问题


I'm writing a c program with an mysql database connection and I'm having difficulties creating my mysql queries...

i want to you a variable integer in my mysql query, but i can't seem to get i right...

my current query looks like this...

mysql_query(conn, "INSERT INTO markerherkenning (MARKER_ID, DATETIME) values(1, CURRENT_TIME())");

my marker_ID value should be a variable value, so i can reduce my code...

i have used this guide to get me going... (http://zetcode.com/tutorials/mysqlcapitutorial)

thanks for helping


回答1:


Something like this:


sprintf(request, "INSERT INTO markerherkenning (%d, DATETIME) values(1, CURRENT_TIME())", marker_id);

At first, you make a string with your request with sprintf (or snprintf), and then use it for sql query.




回答2:


If this is something you need to execute more than once, you might want to use a prepared statement. It's a bit more work, but it buys you some safety and performance. Not to mention you don't have to convert between strings and other types all the time.




回答3:


You have to convert MARKER_ID to string, then append it to the first part of your query and filanny append the rest of it.

char *query = malloc(80);
char num[11];

num = atoi(MARKER_ID);    

strcpy(query, "INSERT INTO markerherkenning (");
strcat(query, num);
strcat(query, ", DATETIME) values(1, CURRENT_TIME())");


来源:https://stackoverflow.com/questions/5940681/mysql-and-c-use-variable-in-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!