Thursday, April 25, 2013

Example of updating a SQLite DB using Xamarin Studio in C#

It took me longer than I'd like to piece this together so I'm sharing a simple example for anyone else looking to make a secure update to a local SQLite database in Android using C#.

static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
 string path = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
 var db = new SQLiteConnection(path,false);
 string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
 string[] parms = new String [] {newText, newValue.ToString(), primaryKey.ToString() };
 var cmd = db.CreateCommand(sql, parms);
 cmd.ExecuteNonQuery();
}