Update/insert table with wrong column name - iOS - ios

I have a table with 5 columns and sometimes I update or insert new entries inside that table. I get the key/values from a json service, but this service added one more field and now when I try to update or insert new entries inside the table I get the error:
Values not inserted. Error: no such column: email
I get that error from this line:
sqlite3_prepare(_database, queryChar, -1, &statement, NULL);
if (sqlite3_step(statement) != SQLITE_DONE)
NSLog(#"Values not inserted. Error: %s",sqlite3_errmsg(_database));
queryChar has this format:
UPDATE contents SET [id] = ?,[phone] = ?,[name] = ?,[websiteurl] = ?,[postalcode]
= ?,[email] = ?,[url] = ? WHERE id = 69
I wonder which is the most effective approach to solve this kind of error. Should I check every column name if it exist in the table and then add it to the queryChar ?

For creating your table you need to create it like
CREATE TABLE IF NOT EXISTS MYTABLENAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT,TABLECOLUMN1 TEXT, TABLECOLUMN2 TEXT, TABLECOLUMN3 TEXT);
Also you have to change your database for adding new column in your database
[its mandatory to alter your table to add new column added later in your existing table]
-(void)ChangeDB:(NSInteger)newDbVersion
{
switch (newDbVersion)
{
case 1:
{
"ALTER TABLE MYTABLENAME ADD COLUMN NEWCOLUMNTOBEADD TEXT"
//run this query in your sqlite
}
break;
default:
break;
}
}
Here is your update query now after fetch data from json where NEWCOLUMNTOBEADD is new data added in your database table at runtime
update MYTABLENAME set TABLECOLUMN1 ='%#', TABLECOLUMN2='%#', TABLECOLUMN3='%#', NEWCOLUMNTOBEADD = '%#' where id ='%#'
More about ALTER command

Related

Using GORM, record is saved into the database, but when i try to retrieve the same entity it gives the saved id+1

def saveTldAndUpdateTimestamp(EntityTld entityTld) {
log.debug("EntityTldService saveTldAndUpdateTimestamp Start")
entityTld.lastUpdated = new Date()
if (!entityTld.dateCreated) {
entityTld.dateCreated = entityTld.lastUpdated
}
EntityTld savedEntityTld = entityTld.save(flush: true, failOnErrors: true)
log.debug("EntityTldService saveTldAndUpdateTimestamp Exit Entity ID:: ${savedEntityTld?.id}")
return savedEntityTld
}
Example : savedEntityTld with id - 200 in the database.
However in the log statement, instead of printing 200, it prints 201 and the rest of the values is similar to the record of id = 200.
FYI, the table corresponding to the domain EntityTld has a GENERATED BY DEFAULT AS IDENTITY column for the id.
The main objective here is, after saving the entitytld record into the database table, i need the saved id and will insert a new record into table2 (this id being one of the columns in table2)

Cannot insert explicit value for identity column in table 'T_PreviewDetails' when IDENTITY_INSERT is set to OFF

I got the above error while trying to insert values to the table 'T_PreviewDetails' through below code.
T_PreviewDetails objprevdet = new T_PreviewDetails();
objprevdet.Title = "preview";
objprevdet.Preview_ID = objprev.ID;
objprevdet.SelectionListDetails_ID = objSelectListDetails.ID;
objprevdet.PreviewStatus_ID = 2;
context.T_PreviewDetails.Add(objprevdet);
context.SaveChanges();
But direct inserting values to the database works fine.Also in 'T_PreviewDetails.cs'
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] is entered.

SQLite id field - autofill

I've added a new table to my DB:
CREATE TABLE myTable (
myId ID NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
PRIMARY KEY(myId, anUniqueTextId) ON CONFLICT IGNORE,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);
Now I want to insert values without manually finding out which index should I put in myId field:
[myDatabase inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:#"INSERT INTO myTable VALUES(?,?,?)",
// #(myData.myId), //I don't want to insert it manually
#(aNumber),
myData.anUniqueTextId,
myData.aText];
if (db.lastErrorCode) {
NSLog(#"Huston, we've got a problem: %#", db.lastError.localizedDescription);
}
}];
Ofc, I get here an error telling:
table myTable has 4 columns but 3 values were supplied
Now the question is how to insert the data to make this field autoinsert myId? I'm not sure if my insert code is invalid or CREATE TABLE statement.
-- UPDATE --
I've updated create statement to correct one:
CREATE TABLE myTable (
myId INTEGER PRIMARY KEY DEFAULT 0 NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);
With respect to your comment you need to specify the PRIMARY KEY with a NULLvalue in the QUERY:
[db executeUpdate:#"INSERT INTO myTable VALUES(?,?,?,?)",
NULL,
#(aNumber),
myData.anUniqueTextId,
myData.aText];
That way the database will fill in the primary key and autoincrement it (SQL Lite specs for PRIMARY KEY).
Here you need to change the schema of table.
To auto insert into myId field, you must have to add constraint AUTOINCREMENT when you create table. Also this field must be use as primary key. So now the schema for table is like:
CREATE TABLE myTable (
myId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);

Adding course to DB (LINQ)

I am trying to add a new record to a table i my database. The code I have adds the record to the table but also throws an exception "System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_COURSE_TAKEN'. Cannot insert duplicate key in object 'dbo.COURSE_TAKEN'. The duplicate key value is (000160228, HIS 155).". Why is it trying to add the record twice? I know for 100% certainty that there is no existing record already present before I try to add it. Below is my code for adding the record:
using (KuPlanEntities db = new KuPlanEntities())
{
var courseTake = new COURSE_TAKEN();
courseTake.Id = "000160228";
courseTake.courseAbNum = courseAbNum;
courseTake.status = status;
courseTake.grade = grade;
db.COURSE_TAKEN.Add(courseTake);
db.SaveChanges();
}

How can I update table in Entity framework?

I am calling a web service from my MVC project and if it is successful then it returns process complete. This result, I am storing in variable called y.
var y = Here pass required parameters and if it is successfull store result in y
when I put breakpoint here and if process complete, I can see result in var y.
So if process complete I need to update my table. For this can I do like this ?
if( y = "Process complete")
{
update table code here
}
and I don't know how to update table in Entity Framework. Here I need to update table called table1 and set column2 = 1, column 3 = value of column 4 where column 1 = value of column 1.
What I know for this is :
UPDATE tableName
SET column2 = 1, column3 = context.FirstOrDefault().column4
WHERE column1 = context.FirstOrDefault(). column1
Update :
Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.
This is the code i am using to update my table :
var rec = (from s in geton.table_1
where s.on_id == geton.table_1.FirstOrDefault().on_id
select s).FirstOrDefault();
rec.export = 1;
rec.on_date = geton.table_1.FirstOrDefault().on_date;
geton.SaveChanges();
A new entity can be added to the context by calling the Add method on DbSet. This puts the entity into the Added state, meaning that it will be inserted into the database the next time that SaveChanges is called.
For example:
using (var context = new YourContext())
{
var record = new TypeName { PropertyName = "Value" };
context.EntityName.Add(record );
context.SaveChanges();
}
For More Info :
http://msdn.microsoft.com/en-us/library/bb336792.aspx
http://msdn.microsoft.com/en-us/data/jj592676.aspx
http://www.entityframeworktutorial.net/significance-of-savechanges.aspx
Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.
That sounds more like a Key error. Are you sure you have put a primary key on that table?
If not then EF just uses the whole table as the key essentially

Resources