Besides snprintf
mentioned in the other answer, you can use the char *sqlite3_mprintf(const char*,...)
function from the sqlite3 API. It uses the sqlite printf
built-in function and it allocates memory for the string using sqlite3_malloc64()
. If everything goes well, it returns a pointer to the string , otherwise it returns NULL
:
int id = 999;
char *sql;
sql = sqlite3_mprintf("INSERT INTO REV_ENTITY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (%d, 'REV', 25, 'Rich-Mond ', 65000.00 )", id);
if (sql != NULL) {
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE3_OK)
/* Do some error handling. */
sqlite3_free(sql);
}
Unlike printf
functions family, sqlite3_mprintf
does not have the luxury to report if the format is not correlated with the arguments. So, if it happens that you use GCC compiler, adding the following code can be useful:
extern char *sqlite3_mprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
The other solution recommended in comments, is to use the sqlite3 prepare, step and finalize functions:
int id = 999;
sqlite3_stmt *stmt = NULL;
char *sql = "INSERT INTO REV_ENTITY (ID,NAME,AGE,ADDRESS,SALARY) " \
" VALUES (?, 'REV', 25, 'Rich-Mond ', 65000.00 )";
sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
/* Bind id. */
sqlite3_bind_int(stmt, 1, id);
if (sqlite3_step(stmt) == SQLITE_DONE) {
printf("Insertion success\n");
} else {
fprintf(stderr, "Insertion error\n");
}
/* Finalize and destroy statement. */
sqlite3_finalize(stmt);