1

I was wondering if it is possible to build a string with the following code

char query[512];
char *insert = "insert into tableName values("%s, "%s");"
strcpy(query, insert);
method("max", "1234"); //function which adds values inro %s

My questions, how can I add another char array into in place of %s if it is possible? Thanks beforehand.

2
  • 1
    Instead of formatting strings, use data binding. Commented Dec 17, 2018 at 3:30
  • 1
    Thanks for your effort I will try that as well sprintf is also working ))) Commented Dec 17, 2018 at 3:38

1 Answer 1

2

use sprintf() so that you can replace the %s with char array https://linux.die.net/man/3/sprintf

char query[512];
char *insert = "insert into tableName values(\'%s\',\'%s\');";
sprintf(query, insert, "max","234");
printf("%s",query);

This is actually a bad approach. This will introduce SQL Injection vulnerabilities.

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

3 Comments

Thank you very very much @jobinrjohnson sprintf that solved my problem)))
Nit - insert should be const char * (see prototype in linked man page) and there is no need to escape single-quotes within double-quotes, e.g. const char *insert = "insert into tableName values('%s','%s');"; is sufficient.
Thanks))) it helped a lot ))

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.