qdb_mprintf()

Print formatted output to a new string

Synopsis:

#include <qdb/qdb.h>

char * qdb_mprintf( const char* fmt,... );

Arguments:

fmt
A pointer to a formatting string to process. The formatting string determines what additional arguments you need to provide. For more information, see printf() in the Neutrino Library Reference.

Library:

qdb

Description:

This function is a variant of sprintf() from the standard C library. The resulting string is written into memory obtained from malloc(), so there is never a possibility of buffer overflow. This function also implements some additional formatting options that are useful for constructing SQL statements.


Note: The qdb_statement() function also allows you to format strings in this way, and doesn't require that you remember to free the resulting string. However, qdb_mprintf() may be useful for building queries from multiple strings.

You should call free() to free the strings returned by this function.

All the usual printf() formatting options apply. In addition, there is a %q option. The %q option works like %s: it substitutes a null-terminated string from the argument list. But %q also doubles every \' character (every escaped single quotation). %q is designed for use inside a string literal. By doubling every \' character, it escapes that character and allows it to be inserted into the string.

For example, suppose some string variable contains text as follows:

      char *zText = "It's a happy day!";

You can use this text in an SQL statement as follows:

      qdb_mprintf(db, "INSERT INTO table VALUES('%q')",
           zText);

Because the %q format string is used, the \' character in zText is escaped, and the SQL generated is as follows:

      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.

The %Q option works like %q except that it also adds single quotes around the outside of the total string. Or, if the parameter in the argument list is a NULL pointer, %Q substitutes the text "NULL" (without single quotes) in place of the %Q option. So, for example, one could say:

    char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
    sqlite3_exec(db, zSQL, 0, 0, 0);
    sqlite3_free(zSQL);

The code above will render a correct SQL statement in the zSQL variable even if the zText variable is a NULL pointer.

Returns:

An escaped string
Success.
NULL
An error occurred (errno is set).

Classification:

QNX Neutrino

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

qdb_snprintf(), qdb_vmprintf(), printf() in the Neutrino Library Reference