Search code examples
c#.netsqlitexamarin.formssqlite-net

How to update an item in database with SQLite in Xamarin forms


I am trying to update the user infos on my app.

I can add a user in my database but when I am trying to update its information, it is not working.

Here is the function that change information:

 public void ChangerLanguageValue(string language)
 {
     var myuser = userinfodatabase.GetUsers();
     myuser.NewsLanguage = language;     
     userinfodatabase.UpdateUserInfos(myuser); // this does not work
 }

Here is my database configuration :

class UserInfosDatabase
{
    private SQLiteConnection conn;

    public UserInfosDatabase()
    {
        conn = DependencyService.Get<ISQLite>().GetConnection();
        conn.CreateTable<MyUser>();
    }

    public string AddUser(MyUser localuser)
    {
        conn.Insert(localuser);
        return "success";
    }

    public MyUser GetUsers()
    {
        var users = (from u in conn.Table<MyUser>() select u);
        return users.ToList().FirstOrDefault();
    }

    //Update
    public string UpdateUserInfos(MyUser localuser)
    {
        conn.Update(localuser);
        return "succes";
    }

}

Solution

  • For SQLite in Xamarin.Forms we could use the plugin sqlite-net-pcl .

    It has very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.

    In your case , you would better update the data as async

    public Task <string>UpdateUserInfos(MyUser localuser) 
    { 
       conn.UpdateAsync(localuser); 
       return "success"; 
    }