Better and also concise way to write a query..(Mysql + C language)
Is there a more concise way to write the following query (using Mysql + C ):
memset(query, 0, 200);
strcat(query, "UPDATE Sconti SET ");
strcat(query, "Sconto = '");
strcat(query, nuovo_sconto);
strcat(query, "' WHERE For_Sconti ='");
strcat(query, For_Sconti);
strcat(query, "' AND Cat_Sconti='");
strcat(query, Cat_Sconti);
strcat(query, "';");
if (mysql_query (conn, query)) {
printf("\nErrore query:\n");
printf("%s", mysql_error(conn),"\n");
The problem is that if I have to update a table having 12 fields, things get annoying..
Tha开发者_开发问答nks, Vera
Depending on the version of MySQL you are using, you can use prepared statements. Check out chapter 20.9 of the MySQL Reference Manual.
With prepared statements you can setup a query like this:
char *queryText = "Update Sconti set Sconto = ? where for_sconti = ? and cat_sconti = ?";
char string[512];
//code to clean the string :)
sprintf(string,"UPDATE Sconti SET Sconto = '%f' WHERE For_Sconti ='%f' AND Cat_Sconti='%f';",scontoValue,forScontiValue,catScontiValue);
Search for sprintf in this page:
http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html
Yep, you can use sprintf
and do something like ...
sprintf(query, "UPDATE Sconti Set "
" Sconto = '%s'"
"WHERE FOR_Sconti = '%s'|
/* etc .... */
";", nuove_sconto, For_Sconti, Cat_Sconti);
Note I use a C trick that in C "a""b"
is equivalent to "ab"
and so equivalet to
"a"
"b"
always sprintf
it's a glorous function that act as a printf but write over a string istead of writing over the standard output. It's very simple to use by everybody since there is no c developer which does not know printf since his first hello world! Adapring it to your code would look like:
char yourString[512];
sprintf(yourString,"UPDATE Sconti SET Sconto = '%f' WHERE For_Sconti ='%f' AND Cat_Sconti='%f';",nuovo_sconto,For_Sconti,Cat_Sconti);
Cheers,
精彩评论