Print formatted output to a new string
#include <qdb/qdb.h> char *qdb_mprintf( const char* format, ... );
qdb
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. The function implements some additional formatting options that are useful for constructing SQL statements.
You should call free() to free the strings returned by this function.
All the usual printf() formatting options apply. The qdb_mprintf() function adds these options:
Suppose some string variable contains the following text:
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 the formatted string is executed.
QNX Neutrino
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |