Requirement :
Check whether a sqlite3 table column is filled or not and if it is not filled, fill up with a value.
I assume that if data is not filled to a field that field will show as NULL.
Following commands I have tried, but the commands are not working for me.
UPDATE SET = 1 WHERE = NULL --> Not working
UPDATE SET = 1 WHERE IS NULL --> Not working
UPDATE SET = 1 WHERE = 0 --> Not working
UPDATE SET = 1 WHERE = '' --> Not working
Below is the c code I am using :
#include <stdio.h> /* needed for vsnprintf */
#include <stdarg.h> /* needed for va_list */
#include <stdlib.h> /* needed for malloc-free */
#include <string.h>
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3 *db;
sqlite3_stmt *stmt;
char *query = NULL, *zErrMsg = 0, *sql = NULL;
char name[20] = "SAM";
int rc, i = 100;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
while (1);
return(0);
}
else {
fprintf(stderr, "Opened database successfully..NEW\n");
}
/* Create a table */
rc = sqlite3_exec(db, "create table demo (name text, age integer);", NULL, NULL, &zErrMsg);
if (rc != SQLITE_OK)
{
printf("Error: %s:Unable to create the table\n", zErrMsg);
while (1);
}
asprintf(&query, "insert into demo (name) values ('%s');", name);
/* Insert into table */
sqlite3_prepare_v2(db, query, strlen(query), &stmt, NULL); /* 2 */
if (sqlite3_step(stmt) == SQLITE_ROW)
{
printf("Inserted successfully\n");
}
if(stmt)
{
sqlite3_finalize(stmt);
stmt = NULL;
}
if(query)
{
free(query);
query = NULL;
}
asprintf(&query, "insert into demo (name, age) values ('%s',%d);", name, i);
/* Insert into table */
sqlite3_prepare_v2(db, query, strlen(query), &stmt, NULL); /* 2 */
if (sqlite3_step(stmt) == SQLITE_ROW)
{
printf("Inserted successfully\n");
}
if(stmt)
{
sqlite3_finalize(stmt);
stmt = NULL;
}
if(query)
{
free(query);
query = NULL;
}
asprintf(&query, "insert into demo (name) values ('%s');", name);
/* Insert into table */
sqlite3_prepare_v2(db, query, strlen(query), &stmt, NULL); /* 3 */
if (sqlite3_step(stmt) == SQLITE_ROW)
{
printf("Inserted successfully\n");
}
if(stmt)
{
sqlite3_finalize(stmt);
stmt = NULL;
}
if(query)
{
free(query);
query = NULL;
}
asprintf(&query, "UPDATE demo SET age = 1 WHERE age = NULL");
stmt = NULL;
rc = sqlite3_prepare_v2(db, query, -1, &stmt, 0);
if (rc == SQLITE_OK)
{
printf("sqlite3_prepare_v2:Executed successfully\n");
}
rc = sqlite3_step(stmt); /* 3 */
if (rc != SQLITE_DONE)
{
printf("ERROR inserting data: %s\n", sqlite3_errmsg(db));
}
if(stmt)
{
sqlite3_finalize(stmt);
stmt = NULL;
}
if(query)
{
free(query);
query = NULL;
}
sqlite3_close(db);
return 0;
}
Thanks in advance