Search code examples
sqlitewindows-8

Update the database record in SqlLite Database


Here my insert code of SQLLite Database in Windows 8 and I want to update the records which are added in database

private async void insert(object sender, RoutedEventArgs e) {
  if (txt1.Text != "" && txt2.Text != "" && txt3.Text != "") {
    var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
    using (var db = new SQLite.SQLiteConnection(dbpath)) {
      // Create the tables if they don't exist
      db.Insert(new person() {
        id= Guid.NewGuid(),
        name = txt1.Text.ToString(),
        address = txt2.Text.ToString(),
        phone = Convert.ToDouble(txt3.Text.ToString()),
      });

      db.Commit();
      db.Dispose();
      db.Close();
    }
  } else {
    throw new NullReferenceException("Enter The Data In Textboxes");
  }
}

Solution

  • In SQLite there's Get<T> method which accept primary key as argument and it will return the row as object. Update method accept the object as parameter and it will update the existing record. Here I am giving you method to update person record.

    private void UpdateRecord(int primaryKey)
    {
        var dbpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
        using (var db = new SQLite.SQLiteConnection(dbpath))
        {
            var objPerson = db.Get<person>(primaryKey);
            objPerson.name = "New name";
            objPerson.address = "New address ";
            objPerson.phone = Convert.ToDouble("New phone number");
            db.Update(objPerson);
            //You don't need to use db.Commit(), db.Dispose() & db.Close() because you are using "using" keyword.
        }
    }