sqlite3 insert fails

This is the relevant part of my code:

  char sHost[]    = "Zomaar een hostnaam";
  char sPath[]    = "Bedenk maar een path als je wilt";
  uint16_t sPort  = 65535;
  char sName[]    = "Een hele mooie naam is altijd mooi";

  /* Create SQL statement */
  /* ==================== */
  sql = "INSERT INTO stations(sHost,sPath,sPort,sName) VALUES (?,?,?,?)",(sHost,sPath,sPort,sName);

  //sql = "INSERT INTO stations(sHost,sPath,sPort,sName) VALUES ('sHost url','sPath value',80,'sName station')";

The un-commented statement fails
The commented works just fine but is not very flexible.

The error message is:
Opened database successfully
SQL error: NOT NULL constraint failed: stations.sHost
Program ended with exit code: 0

While it's clear that sHost in NOT NULL.

**Any suggestion would be most **helpful

Look up bind variables for sqlite3.

Alternatively, use sprintf to populate the values from your variables into the sql string.

what's sql variable type ??

 sql = "INSERT INTO stations(sHost,sPath,sPort,sName) VALUES (?,?,?,?)",(sHost,sPath,sPort,sName);

This does not sound like proper C++
it just assigns sName to sql given the way the comma works in statements.

@wildbill
Thanks for the reply, but I don't understand what you mean by formatting the string I wish to put in the db.
"The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str."
Can, will, you provide an example please?

if sql is a char buffer large enough

char sql[200];
...
sprintf(sql, "INSERT INTO stations(sHost,sPath,sPort,sName) VALUES ('%s','%s','%s','%s')", sHost,sPath,sPort,sName);

your issue with your previous code is that when you do x = (a, b, c); in c++, the compiler evaluates a, b and then c and stores the result of evaluating c into x.

@J-M-L
The sprintf did the trick!
I've to change this:
char sSql[200];
char *sql = sSql;
but it works.
Thank you.

@ wildbill
Can, will, you please point me to an explanation/tutorial on how this "Look up bind variables for sqlite3. " thing works?

if you already had a buffer you could have used that directly, you don't need to have the extra pointer

 sprintf([color=red]sSql[/color], "INSERT ...

Your right, but when I try to list the db records, my compiler complains with: "Array type 'char [200]' is not assignable". So I leave it as is.

very weird... would need to see some real code

Just to help other people making their search for that "bindings" thing a little easier, I've found this: "https://www.whoishostingthis.com/compare/sqlite/optimize/".
Its a good explanation of What, How and Why. To find information on the working of statements, as usual, mr. G. is your friend.

Even better! https://zetcode.com/db/sqlitec/

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.