Chu
Chu

Reputation: 750

Format specifier for real types in sqlite3

I am trying to insert values into a table in sqlite3 db which contain REAL type columns using C. I want to know the format specifier for real types.

psql = "insert into %q \ (xyz_id, num_of_xyz, time, total, used, rem) values \ ('%q', %i, %i, ?, ?, ?);";

and execute it with sqlite3_exec()

here total, used and rem are REAL types. So what is the format specifier to be used (?), i tried with '%i' but its not working.

Thanks in advance

Upvotes: 1

Views: 552

Answers (1)

CL.
CL.

Reputation: 180060

sqlite3_mprintf is a C function and uses C types; %i is for int values. A floating-point value would be formatted with %f.

(Please note that %q uses escaping that works only inside SQL strings; you cannot format table names with that.)

In any case, it would be counterproductive to convert the value into text, just to be parsed back into a floating-point value again by the database. A better way would be to use a prepared statement, so that you can use the parameter binding functions, like this:

sqlite3 *db = ...;
const char *sql = "INSERT INTO MyTable(xyz_id, num_of_xyz, time, total, used, rem)"
                  " values (?,?,?,?,?,?)";
sqlite3_stmt *stmt;

if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
  printf("error: %s\n", sqlite3_errmsg(db));
} else {
  sqlite3_bind_text  (stmt, 1, "xyz ID", -1, SQLITE_TRANSIENT);
  sqlite3_bind_int   (stmt, 2, 123);
  sqlite3_bind_int   (stmt, 3, 456);
  sqlite3_bind_double(stmt, 4, 1.23);
  sqlite3_bind_double(stmt, 5, 4.56);
  sqlite3_bind_double(stmt, 6, 7.89);
  if (sqlite3_step(stmt) != SQLITE_DONE)
    printf("error: %s\n", sqlite3_errmsg(db));
  sqlite3_finalize(stmt);
}

Upvotes: 2

Related Questions