我一直在使用SQLite帮助程序类here来从我的应用程序向数据库添加和检索数据。
我最终得到了许多类似的方法,唯一的区别是SQLite表名和从数据对象到表的转换,反之亦然。
有没有更简洁的方法来使这些方法对于任意数量的字段和数据类型更通用?
(真正的标题名称已被更改!)
2种插入方法的示例:
private void AddProgresstoDb(DataObj.Progress progress)
{
//INSERT SQlite
SQLiteDatabase db = new SQLiteDatabase();
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("fieldAA", progress.fieldAA.ToString());
data.Add("fieldAB", progress.fieldAB);
data.Add("fieldAC", progress.fieldAC.ToString());
data.Add("fieldAD", progress.fieldAD.ToString("yyyy-MM-dd HH:mm:ss"));
data.Add("fieldAE", progress.fieldAE.ToString("yyyy-MM-dd HH:mm:ss"));
data.Add("fieldAF", progress.fieldAF);
data.Add("fieldAG", progress.fieldAG.ToString());
data.Add("fieldAH", progress.fieldAH.ToString());
data.Add("fieldAI", progress.fieldAI.ToString());
try
{
db.Insert("tableProgress", data);
}
catch (Exception ex)
{
//Handle error
}
}
private void AddResulttoDb(DataObj.Result result)
{
//INSERT SQlite
SQLiteDatabase db = new SQLiteDatabase();
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("fieldBA", result.fieldBA.ToString());
data.Add("fieldBB", result.fieldBB);
data.Add("fieldBC", result.fieldBC.ToString());
data.Add("fieldBD", result.fieldBD.ToString("yyyy-MM-dd HH:mm:ss"));
data.Add("fieldBF", result.fieldBF);
try
{
db.Insert("tableResult", data);
}
catch (Exception ex)
{
//Handle error
}
}
1 GetDataTable方法的示例:
private ObservableCollection<DataObj.Progress> GetProgressfromDb()
{
var progress = new ObservableCollection<DataObj.Progress>();
//QUERY SQlite
try
{
SQLiteDatabase db = new SQLiteDatabase();
DataTable prog;
String query = "select * from tableProgress;";
prog = db.GetDataTable(query);
foreach (DataRow r in prog.Rows)
{
progress.Add(new DataObj.Progress()
{
fieldAA = Convert.ToInt32(r["fieldAA"]),
fieldAB = r["fieldAB"].ToString(),
fieldAC = (DateTime)r["fieldAC"],
fieldAD = (DateTime)r["fieldAD"],
fieldAE = r["fieldAE"].ToString(),
fieldAF = (decimal)r["fieldAF"],
fieldAG = (decimal)r["fieldAG"],
fieldAH = r["fieldAH"].ToString(),
fieldAI = (decimal)r["fieldAI"]
});
}
}
catch (Exception ex)
{
//Handle error
}
return progress;
}