qdb_mprintf()
Print formatted output to a new string
Synopsis:
#include <qdb/qdb.h> char *qdb_mprintf( const char* format, ... );
Arguments:
- format
- A pointer to a formatting string to process. This string determines what additional arguments you need to provide. For more information, see printf() in the QNX Neutrino C Library Reference.
Library:
qdbDescription:
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.
- %q
- This option works like %s: it substitutes a null-terminated string from the argument list; however, %q also doubles each single-quote character ('). This is useful inside a string literal. By doubling each single-quote character, %q escapes that character and allows it to be inserted into the SQL statement.
- %Q
- This option works like %q except that it adds single quotes around the contents of the entire string. Or, if the parameter in the argument list is a NULL pointer, %Q substitutes the text NULL in place of the %Q option.
- %z
- This option works like %s except that after the source string (which is the argument that %z refers to) has been copied into the formatted string, the source string memory doesn't have to be freed.
Returns:
- A pointer to an escaped string
- Success.
- NULL
- An error occurred (errno is set).
Examples:
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.
Classification:
QNX Neutrino
| Safety: | |
|---|---|
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |
