Print formatted output to a new string
#include <qdb/qdb.h> char *qdb_mprintf( const char* format, ... );
This function is a variant of sprintf() from the standard C library. The resulting string is written into memory obtained from malloc(), so there's no possibility of buffer overflow. You must call free() to free the strings returned by this function.
Suppose some string variable is initialized as follows:
char *zText = "It's a happy day!";
You can use this text in an SQL statement as follows:
qdb_mprintf("INSERT INTO table VALUES('%q')", zText);
Because the %q formatting option is used, the single-quote character in zText is escaped and the generated SQL is:
INSERT INTO table1 VALUES('It''s a happy day!')
This is correct. Had you used %s instead of %q, the generated SQL would have looked like this:
INSERT INTO table1 VALUES('It's a happy day!');
This second example is an SQL syntax error. As a general rule, you should always use %q instead of %s when inserting text into a string literal.
Suppose you're unsure if your text reference is NULL. You can use this reference as follows:
char *zSQL = qdb_mprintf("INSERT INTO table VALUES(%Q)", zText);
The code above will render a correct SQL statement in the zSQL variable even if the zText variable is a NULL pointer.
The %z option is handy for nested strings:
char id[] = "12345678"; char *nested = qdb_mprintf( "SELECT msid FROM mediastores WHERE id = %Q", id); char *sql = qdb_mprintf( "DELETE FROM library WHERE msid = (%z);", nested); qdb_exec(sql); free(sql);
The nested string doesn't have to be freed after it gets copied into the formatted string and the SQL code within that string is executed.
QNX Neutrino
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |