sqlite - 如何在 SQLite 中存储唯一的类实例?
问题描述
我正在尝试将一些信息作为类实例存储在 SQLite 表中。实例的 DateTime 属性必须是唯一的。我对数据库编程完全陌生,我不太了解如何在 Xamarin 中使用 SQLite。创建新实例时,如果它们在 DateTime 属性中匹配,则需要更新表中的现有实例。
SQLiteAsyncConnection connection = new SQLiteAsyncConnection(App.FilePath);
await connection.CreateTableAsync<ModulInformationData>();
ModulInformationData data = new ModulInformationData();
data.InitModulInformation(modul);
int rows = 0;
try
{
rows = await connection.UpdateAsync(data);
}catch(Exception e)
{
Console.WriteLine("SQL Update failed " + e.Message);
}
Console.WriteLine("rows updated: " + rows);
if (rows == 0)
{
Console.WriteLine("before insert");
try
{
int key1 = await connection.InsertAsync(data);
Console.WriteLine("after insert: " + key1);
}catch (Exception e)
{
Console.WriteLine("SQL insert failed " + e.Message);
}
}
ModulInformationData 类
public class ModulInformationData
{
[PrimaryKey,AutoIncrement]
public int Id { get; set; }
[Unique]
public DateTime tidspunkt { get; set; }
other properties...
目前,我在插入时遇到错误,但消息仅显示“约束”。我能做些什么来完成这项工作?
解决方案
你想达到这样的GIF效果吗。</p>
首先,您可以为数据库 CRUD 创建一个类。
public class NoteDatabase
{
readonly SQLiteAsyncConnection _database;
public NoteDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Note>().Wait();
}
public Task<List<Note>> GetNotesAsync()
{
return _database.Table<Note>().ToListAsync();
}
public Task<Note> GetNoteAsync(int id)
{
return _database.Table<Note>()
.Where(i => i.ID == id)
.FirstOrDefaultAsync();
}
public Task<int> SaveNoteAsync(Note note)
{
if (note.ID != 0)
{
return _database.UpdateAsync(note);
}
else
{
return _database.InsertAsync(note);
}
}
public Task<int> DeleteNoteAsync(Note note)
{
return _database.DeleteAsync(note);
}
}
然后是模型类。
public class Note
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Text { get; set; }
[Unique]
public DateTime Date { get; set; }
public string Gender { get; set; }
}
如果我们想将数据添加或更新到数据库中,首先我们应该将数据更新到实例中,然后我们可以像下面的保存点击事件一样将此实例保存到数据库中。
async void OnSaveButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
note.Date = DateTime.UtcNow;
note.Gender = (string)myPicker.SelectedItem;
await App.Database.SaveNoteAsync(note);
await Navigation.PopAsync();
}
这是我的演示。你可以下载它并参考它。
推荐阅读
- r - R: if values of two columns of two data frames are equal, add column of one of the two data frames
- javascript - 启动调试前的 npm 任务
- node.js - 以编程方式取消 MongoDB 事务
- azure-ad-b2c - 有没有办法在 AD B2C 中显示不存在的用户帐户因错误尝试次数过多而导致帐户锁定之类的消息?
- html - 当其余内容为 iframe 时,在页面顶部放置警报横幅
- sql - 为什么我必须在此列上使用聚合函数?
- android - 如何安装CameraView
- java - 即使应用程序被杀死,我怎样才能让我的应用程序运行?从最近的应用程序中删除它时被杀死
- javascript - 为什么在 for 循环中使用 document.getElementById('').innerHTML 和 document.write() 的结果不一样?
- python - 与列表中的前缀和后缀单词匹配并返回一个包含所有链接单词的字符串