SQLite Update table - c++

Trying to update table by user specified values. But the values are not getting updated.
cout<<"\nEnter Ac No"<<endl;
cin>>ac;
cout<<"\nEnter Amount"<<endl;
cin>>amt;
/* Create merged SQL statement */
sql = "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac;
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
If I replace BAL and ACCOUNT_NO by some integer value instead of place holder then it is working fine.

Your sql string is not being created properly.
If you expect this code
sql = "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac;
to result in
"UPDATE RECORDS set BAL = '1' where ACCOUNT_NO = '2'"
where
amt= 1 and ac = 2 then you need to use a string formatting call like this.
// the buffer where your sql statement will live
char sql[1024];
// write the SQL statment with values into the buffer
_snprintf(sql,sizeof(sql)-1, "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac);
buff[sizeof(sql)-1]='\0';
On your particular platform _snprintf(...) might be snprintf(..) or another similarly named function. Also your compiler may warn about buffer manipulation security vulnerabilities. Choose the appropriate substitute for your needs

Related

WHERE column = value, only work with INTEGER value

I use sqlite on a c++ project, but I have a problem when i use WHERE on a column with TEXT values
I created a sqlite database:
CREATE TABLE User( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(24))
When i try to get the value of the column with VARCHAR values, it doesn't work, and return me a STATUS_CODE 101 just after the sqlite3_step :
int res = 0;
sqlite3_stmt *request;
char *sqlSelection = (char *)"SELECT * FROM User WHERE name='bob' ";
int id = 0;
res = sqlite3_prepare_v2(db, sqlSelection, strlen(sqlSelection), &request, NULL);
if (!res){
while (res == SQLITE_OK || res == SQLITE_ROW){
res = sqlite3_step(request);
if (res == SQLITE_OK || res == SQLITE_ROW ){
id = sqlite3_column_int(request, 0);
printf("User exist %i \n",id);
}
}
sqlite3_finalize(request);
I also tried with LIKE but it also doesn't work
SELECT * FROM User WHERE name LIKE '%bob%'
But when I execute the same code but for an INTERGER value
SELECT * FROM User WHERE id=1
It work fine.
In DB Browser for SQLite all requests work fine.
To solve the problem I searched what status code 101 means.
Here is what they said.
(101) SQLITE_DONE
The SQLITE_DONE result code indicates that an operation has completed.
The SQLITE_DONE result code is most commonly seen as a return value
from sqlite3_step() indicating that the SQL statement has run to
completion. But SQLITE_DONE can also be returned by other multi-step
interfaces such as sqlite3_backup_step().
https://sqlite.org/rescode.html
So, you're getting 101 because there is no more result from SELECT SQL.
The solution was to replace the VARCHAR fields by TEXT.
SQLite for c++ seems to don't manage VARCHAR fields when they are used after the WHERE

Getting number of columns in a table using ' Proc C-C``

I am using the below code to get the number of columns in an oracle table.
char selectQuery[30000] = {'\0'};
strcpy(selectQuery, "SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME=\'");
strcat(selectQuery, tableName);
strcat(selectQuery, "\'");
strcpy((char*) stmt.arr, selectQuery);
stmt.len = strlen((char*) stmt.arr );
stmt.arr[stmt.len]= '\0';
EXEC SQL WHENEVER SQLERROR CONTINUE;
EXEC SQL WHENEVER NOT FOUND CONTINUE;
EXEC SQL DECLARE SELECTCOLNU STATEMENT;
EXEC SQL PREPARE SELECTCOLNU FROM :stmt;
if(sqlca.sqlcode != 0)
{
DEBUG_LOG("SQL-ERR:Preparation of SELECT Query to get number of columns failed: Ora-Err: %d %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
return PREPARATION_FAILURE;
}
EXEC SQL EXECUTE SELECTCOLNU INTO:columnsNo;
if(sqlca.sqlcode < 0)
{
DEBUG_LOG("SQL-ERR:Execute failed: Ora-Err: %d %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
return EXECTUION_FAILURE;
}
DEBUG_LOG("Number of columns: %d\n", columnsNo);
When I execute the code, It doesn't give any error but I am getting "Number of columns: 0" as the output.
There are few columns in the table I am referring.
Am I doing anything wrong here?
Below is the declaration section...
EXEC SQL BEGIN DECLARE SECTION;
int columnsNo;
VARCHAR stmt[MAX_SQL];
EXEC SQL END DECLARE SECTION;
Don't "escape" the ' in a C- string. It will have \' just in the string, and that is not what you want because the ' is the database string quote, which you now escape for the database and the database doesn't understand the query now.
sprintf(selectQuery, "SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME='%s'", tableName);
Note:
stmt.len = strlen((char*) stmt.arr );
stmt.arr[stmt.len]= '\0';
In the above strlen counts the number of characters until a null character. Thus stmt.arr[stmt.len] is already null. (No harm, though.)

ORA-00947: not enough values when creating object in Oracle

I created a new TYPE in Oracle in order to have parity between my table and a local c++ object (I am using OCCI interface for C++).
In the code I use
void insertRowInTable ()
{
string sqlStmt = "INSERT INTO MY_TABLE_T VALUES (:x)";
try{
stmt = con->createStatement (sqlStmt);
ObjectDefinition *o = new ObjectDefinition ();
o->setA(0);
o->setB(1);
o->setC(2);
stmt->setObject (1, o);
stmt->executeUpdate ();
cout << "Insert - Success" << endl;
delete (o);
}catch(SQLException ex)
{
//exception code
}
The code compiles, connects to db but throws the following exception
Exception thrown for insertRow Error number: 947 ORA-00947: not enough
values
Do I have a problematic "sqlStmt"? Is something wrong with the syntax or the binding?
Of course I have already setup an environment and connection
env = Environment::createEnvironment (Environment::OBJECT);
occiobjm (env);
con = env->createConnection (user, passwd, db);
How many columns are in the table? The error message indicates that you didn't provide enough values in the insert statement. If you only provide a VALUES clause, all columns in the table must be provided. Otherwise you need to list each of the columns you're providing values for:
string sqlStmt = "INSERT INTO MY_TABLE_T (x_col) VALUES (:x)";
Edit:
The VALUES clause is listing placeholder arguments. I think you need to list one for each value passed, e.g.:
string sqlStmt = "INSERT INTO MY_TABLE_T (GAME_ID, VERSION) VALUES (:x1,:x2)"
Have a look at occidml.cpp in the Oracle OCCI docs for an example.

How to Compare my sql columns dynamically

I am not able to get idea about the following requirement. The example table follows.
CREATE TABLE `test` (
`Id` INT NOT NULL,
`Name` VARCHAR(45) NULL,
`did_fk` INT NULL,
`adid_fk` INT NULL,
PRIMARY KEY (`Id`));
INSERT INTO test (id,name,did_fk,adid_fk)
VALUES
(1,'Rajesh',1,1),
(2,'Neeli',2,2),
(3,'Satish',3,3),
(4,'Ganesh',4,5),
(5,'Murali',9,10);
Here I need to compare the "id" with _fk columns i.e. did_fk & adid_fk. The "id" should be equal to did_fk & as well as adid_fk. If any of them is not true, then I should get that row.Here I need to get the rows 4 & 5.Since "_fk" columns are not equal to "id" value.Problem is "_fk" columns are not fixed. But "id" name is fixed.
SELECT * FROM `test` WHERE `Id` != `did_fk` OR `Id` != `adid_fk`
If your dynamic columns ends with _fk or some another suffix you can try to create SP like following
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetNonEqualFkValues`(IN tableName varchar(255))
BEGIN
DECLARE c_name VARCHAR(255);
DECLARE done INT DEFAULT FALSE;
DECLARE curs CURSOR FOR select column_name from information_schema.columns where column_name like '%_fk';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs;
SET #q = concat("SELECT * FROM ", tableName, " WHERE 1!=1 ");
get_col: LOOP
FETCH curs INTO c_name;
IF done THEN
LEAVE get_col;
END IF;
SET #q = CONCAT(#q, " OR ", c_name," != id");
END LOOP get_col;
PREPARE stmt1 FROM #q;
EXECUTE stmt1;
END
And then invoke for concrete table like
call GetNonEqualFkValues('test')
The code isn't perfect, but it works for me and I think idea should be clear.

mysql returns null when asking for difference between some value and null

in my table i have 3 column
id, somevalue (float), current timestamp
code below searches for the latest value in today's date and subtracts that with the value on monday of the same week. but i dont have any value stored for monday in this week so its NULL at the moment. but result of below code should be some value not null ???? dont understand how is it possible. pls explain.
select(SELECT power FROM newdb.newmeter
where date(dt)=curdate() order by dt desc limit 1)-
(select Power from newdb.newmeter
where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));
as i was reading the similar questions-answers it looks like anything you do with null in mysql is null is it true??
if yes how do i resolve this
update:
i tried this but didnt work
select sum(amount) - coalesce(sum(due),0)
just wanted to add something more to this
i'm calling querydb as following for the mysql in c++
bool Querydb(char *query, double Myarray[1024])
{
//snip//
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return 0;
}
else {
res = mysql_use_result(conn);
//output table name
//printf("MySQL Tables in mysql database:\n");
//checking for null value in database
while((row = mysql_fetch_row(res))==NULL){
printf("ERROR_____NULL VALUE IN DATABASE ");
return 0;
}
//if not null then ...
while ((row = mysql_fetch_row(res)) != NULL){
printf("rows fetched %s\n", row[0]);
sprintf(buffer,"%s",row[0]);
value1 = atof(buffer);
Myarray[i]=value1;
//printf("Myarray in sql for daybutton = %f\n",Myarray[i]);
i++;
}
i=0;
//for(i=0;i<5;i++){
// printf("mya arr in sqlfunction = %f\n",Myarray[i]);}
return 1;
}
printf("if here then....where??\n");
//close connection
// mysql_free_result(res);
//return 0;
}
the above function works ok with different query when database has null but doesnt work with this query
select(SELECT power FROM newdb.newmeter
where date(dt)=curdate() order by dt desc limit 1)-
(select Power from newdb.newmeter
where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));
it returns 1 even thought the answer is NULL...
Consult the manual on working with NULL values. They are treated specially http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html
What value would you want it to be? This isn't particularly specific to MySQL - operations involving null operands (including comparisons) have null results in most SQL dialects.
You may want to use COALESCE() to provide a "default" value which is used when your real target value is null.
work Around would be
select(SELECT power FROM newdb.newmeter
where date(dt)=curdate() order by dt desc limit 1)-
(select COALESCE(Power,0) from newdb.newmeter
where date(dt)=(select date(subdate(now(), interval weekday(now()) day))));