Creating a SQLite table row updating row again and again - android-sqlite

I have created a table for my application... first time user will give the input for two editText ,name and mobile number when table is empty after that only updating the first row of table...so on

A scenario:
add a new record with name:"name1", telephone: "123456789" --> new record
add a new record with name:"name2", telephone:"987654321" --> update the previously entered record.
If that what you want then:
be sure to always insert the new record with the same id as the previously inserted one.
use db.insertWithOnConflict()[ link ] to insert new records, passing the value CONFLICT_REPLACE [ link ] for the last parameter conflictAlgorithm
Sample Code
void Add_Contact(Person_Contact contact)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// SINGLE_ROW_ID is a constant holding the single row id that will be used. e.g: SINGLE_ROW_ID = 1
values.put( KEY_ID, SINGLE_ROW_ID );
values.put( KEY_NAME, contact.get_name() ); // Contact Name
values.put( KEY_PH_NO, contact.get_phone_number()); // Contact Phone
// Inserting Row
db.insert( TABLE_CONTACTS, null, values );
db.insertWithOnConflict( TABLE_CONTACTS,KEY_ID,values, SQLiteDatabase.CONFLICT_REPLACE );
db.close(); // Closing database connection
}

Related

Trigger not working for Update an insert operation

**i am trying to do upsert operatiob on my timesheet__c object
Trigger is on Leave__c object which is trying to match the date
if date is same then check for employee name
and if name found on timeSHeet__c object then just update
if not found then Crate an new Record on TimeShett__c object **
i having two Objects
child-Leave__c;
Parent-TimeSheet__c;
when ever i insert a record on leave object
1.it should check whether on same date is there any timesheet record
here the trigger
'''
trigger CheckTime on LEAVE__c (after insert) {
list<id> idList=new list<id>();
for(Leave__c ls:Trigger.new)
{
idList.add(ls.id); //adding new record id
}
list<Leave__c> lslist=[select id ,Date__c,Hours__c,Employee__c,TimeSheet_Lookup__r.Date__c,TimeSheet_Lookup__r.Employee__c,TimeSheet_Lookup__r.Hours__C from LEAVE__c where id IN:idList]; //fetching new record using child to parent relationship
list<TimeSheet__c> tslist=new list<TimeSheet__c>();
for(Leave__c ls:lslist)
{
if(ls.Date__c==ls.TimeSheet_Lookup__r.Date__c)//checking if date is matching
{
if(ls.Employee__c==ls.TimeSheet_Lookup__r.Employee__c )//checking if employee name is matching
{
ls.TimeSheet_Lookup__r.Hours__c=ls.Hours__c;
lslist.add(ls);
update lslist;
}
else
{
TimeSheet__c ts=new TimeSheet__c();
ts.Employee__c=ls.Employee__c;
ts.Hours__c=ls.Hours__c;
ts.Date__c=ls.Date__c;
tslist.add(ts);
}
}
}
insert tslist;
}
'''

EntityFramework, problems to create entity with composit key

I have a database first project and the context/entities are automatically generated with Scaffold-DbContext.
One table (Region_User) in the database is a cross reference table between User and Region, it contains only two fields UserId, and RegionId that together is the composit key for the table.
I'm currently trying to add a new Region_User to a user like below:
var userregions = new List<Region_User>();
userregions.Add(new Region_User { UserId = 1, RegionId = 1 });
user.Region_User = userregions;
and then try to save it to the database I get an error like:
{"Entity type 'Region_User' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method."}
The generated entity Region_User only contains the fields UserId and RegionId..
How should I do to save a new row in the Region_User table?

Fetching id field of an entity in the SQL Transaction

I have the following schema.
Person(pid, pname)
Beer(bid, bname)
Likes(pid,bid)
I would like to insert a likes item. However, I am accepting the following format for the new users : (Pid, pname, bid, bname).
I would like to create a transaction for that to avoid conflict ( This is a highly simplified version of my real problem but the issue is the same). In my Person table, I set pid Auto-Increment(or Serial in Postgresql). Also the same goes for bid.
I have stuck in a point where I know the Person does not exist but the beer exists. So, I have to create a Person, then add an entity to Likes relation.
As far as I know, when I use the Autocommit(false) in dB, the transaction won't save until the commit. So, should I change the db design:
Change the auto-increment field to a normal integer, not null field.
In the transaction, after the autoCommit(false) has begun, read the last entry of the person
Increment it by one while creating the new person
Then create likes relation
Or, is there any other way around or do I miss something about transactions?
Here is what I have done so far:
try {
String add_person_sql = "INSERT INTO Person (name) VALUES(?)";
PreparedStatement add_person_statement = mydb.prepareStatement(add_person_sql);
String add_likes_sql = "INSERT INTO Likes (pid, bid) VALUES(?, ?)";
PreparedStatement add_likes_statement = mydb.prepareStatement(add_likes_sql);
mydb.setAutoCommit(false);
add_person_statement.setString(1, pname);
// The problem is, without saving the person I cannot know the id of the person
// AFAIK, this execution is not finished until commit occurs
add_person_statement.executeQuery();
// How can I fetch person's id
add_likes_statement.setString(1, pid);
add_likes_statement.setString(2, bid);
add_likes_statement.executeQuery();
mydb.commit();
}
catch(Exception e){
System.out.println(e);
mydb.rollback();
}
You can tell JDBC to return the generated ID from the insert statement, then you can use that ID to insert into the likes table:
mydb.prepareStatement(add_person_sql, new String[]{"pid"});
The second parameter tells the driver to return the generated value for the pid column.
Alternatively you can use
mydb.prepareStatement(add_person_sql, Statement.RETURN_GENERATED_KEYS);
that tells the driver to detect the auto increment columns.
Then run the insert using executeUpdate()
add_person_statement.setString(1, pname);
add_person_statement.executeUpdate();
int newPid = -1;
ResultSet idResult = add_person.getGeneratedKeys();
if (idResult.next()) {
newPid = idResult.getInt(1);
}
add_likes_statement.setString(1, newPid);
add_likes_statement.setString(2, bid);
add_likes_statement.executeUpdate();
mydb.commit();

Prevent duplicate values on bulk insert (Salesforce)

I need a trigger that receives data from users (Bulk load of about 1000 records) and store them in a Salesforce database. The problem is that users can show up more than once in Trigger.new or even on a different batch. The custom object name is CBK_User and has an EXTERNAL_ID (unique) called USER_ID. In my code I check that the users does not yet exist in the database:
Map<String, CBK_User__c> users = new Map<String,CBK_User__c>
([select Id, USER_ID__c from CBK_User__c where USER_ID__c in : userIds]);
(userIds has the external ids of the Trigger.new objects)
When a I try to insert, it gives me the error:
DUPLICATE_VALUE, duplicate value found: USER_ID__c duplicates value on
record with id: a1QJ0000000HRd8"
How do I prevent duplicate values on bulk insert?
I've adapted your problem to this basic example (Exercise 2: Lead duplicate prevention)
You should clean first the "new" list from duplicated entries, and then clean from existing in db.
trigger CBK_UserDuplicatePreventer on CBK_User__c (before insert, before update) {
//Enter a map declaration to hold records which we will add,
// this will become a unique map, no duplicate values within it.
Map<String, CBK_User__c> cbkUserMap = new Map<String, CBK_User__c>();
//The next few lines loop across the array of records that are passed into
//the trigger in bulk fashion from any API or User Interface database operation.
//The goal of this loop is to ensure that there are no duplicates within
//the batch that we have received and to gather a list of externalIds that we will use later
for (CBK_User__c cbkUser : System.Trigger.new) {
/* Make sure we don't treat an externalId that
isn't changing during an update as a duplicate. */
if ((cbkUser.USER_ID__c != null) && (System.Trigger.isInsert ||
(cbkUser.USER_ID__c != System.Trigger.oldMap.get(cbkUser.Id).USER_ID__c))) {
// Make sure another new CBK_User__c isn't also a duplicate
if (cbkUserMap.containsKey(cbkUser.USER_ID__c)) {
cbkUser.USER_ID__c.addError('Another new CBK_User__c has the same USER_ID.');
} else {
cbkUserMap.put(cbkUser.USER_ID__c, cbkUser);
}
}
}
// Using a single database query, find all the CBK_User__c in
// the database that have the same USER_ID as ANY
// of the CBK_User__c being inserted or updated. */
for (CBK_User__c cbkUser : [SELECT USER_ID__c FROM CBK_User__c WHERE USER_ID__c IN :cbkUserMap.KeySet()]) {
CBK_User__c newCbkUser = cbkUserMap.get(cbkUser.USER_ID__c);
newCbkUser.USER_ID__c.addError('A CBK_User__c with this USER_ID already exists.');
}
}

I dont want to insert the PK val.But - Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF

I am using the Entity Framework to update my database.
The Employee table has an employeeId primary key field.
When I instantiate an employee object, the employeeId defaults to zero.
I want to insert the employee object into the database, ignoring the primary key value of zero.
Yet I get this exception;
Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF.
What should I be doing to stop this?
public void Add()
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
// Set default values
this.StartDate = DateTime.Now;
// Start date now
this.SHP_UserRoleId = db.SHP_UserRoles.Where(x => x.RoleName == "Employee").Single().UserRoleId;
// Default user role is "Employee". This can be changed later.
this.DepartmentId = 1;
// This is a temporary fix.
db.AddToEmployees(this);
//db.Employees.AddObject(this);
db.SaveChanges();
}
}
I fixed the problem.
I updated the database and I forgot to update my edmx file to reflect that change.