时间:2021-01-17 14:08:56 | 栏目:.NET代码 | 点击:次
1.Metro中使用SQLite数据库具体步骤如下:
1).下载SQLite for WinRT
地址:http://www.sqlite.org/download.html
下载Precompiled Binaries for Windows Runtime,这是一个Visual Studio的一个扩展,文件以vsix为后缀,直接双击运行即可。(如下图)
2).为项目添加引用
创建一个项目,在解决方案在选择“引用->添加引用”,在引用管理器的左边列表中选择Windows->扩展,然后再右边的列表中选中如下图所示:
注意:选择 SQLite for Windows Runtime 和 Microsoft Visual C++ Runtime Package
3). 为项目添加C# 驱动
在解决方案中,选择项目,单击右键,选择“管理NuGet程序包”,在管理器中进行如下图的操作:
安装完成后,你的项目的根目录下会多出两个文件:SQLite.cs和SQLiteAsync.cs文件,我们就可以通过这两个类来操作SQLite了。
2.创建数据库
1).首先:声明一个MemberInfo类也就是表主键自动增长
{
[SQLite.AutoIncrement, SQLite.PrimaryKey]
public int ID { set; get; }
public string Name { set; get; }
public int Age { set; get; }
public string Address { set; get; }
}
string path =Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Member.sqlite"); //数据文件保存的位置
using (var db = new SQLite.SQLiteConnection(path)) //打开创建数据库和表
{
db.CreateTable<MemberInfo>();
}
}
{
try
{
using (var db = newSQLiteConnection(path))
{
db.Insert(data);
}
}
catch(Exception e)
{
throw e;
}
}
publicvoid Delete(int id)
{
try
{
T data = Select(id);
using (var db = newSQLiteConnection(path))
{
db.Delete(data);
}
}
catch(Exception e)
{
throw e;
}
}
public void Insert(T data)
{
try
{
using (var db = newSQLiteConnection(path))
{
db.Insert(data);
}
}
catch(Exception e)
{
throw e;
}
}
publicvoid Delete(int id)
{
try
{
T data = Select(id);
using (var db = newSQLiteConnection(path))
{
db.Delete(data);
}
}
catch(Exception e)
{
throw e;
}
}
public MemberInfo Select(int id)
{
try
{
MemberInfo data = null;
using (var db = newSQLiteConnection(path))
{
List<object> obj = db.Query(newTableMapping(typeof(MemberInfo)), string.Format("Select * from MemberInfo where ID={0}", id));
if (obj != null&&obj.Count>0)
{
data = obj[0] as MemberInfo;
}
}
return data;
}
catch (Exception e)
{
throw e;
}
}
publicvoid Updata(MemberInfo data)
{
try
{
using (var db = newSQLiteConnection(path))
{
db.Update(data);
}
}
catch(Exception e)
{
throw e;
}
}
publicObservableCollection<MemberInfo> SelectAll()
{
ObservableCollection<MemberInfo> list = newObservableCollection<MemberInfo>();
using (var db =newSQLiteConnection(path))
{
List<object> query = db.Query(newTableMapping(typeof(MemberInfo)), "select * from MemberInfo");
foreach (var mem in query)
{
MemberInfo info = mem asMemberInfo;
list.Add(info);
}
}
return list;
}