标签:bsp void 数据库访问 insert current arc sed EDA ima
一、添加System.Data.SQLite引用
二、添加linq2db引用
三、新建实体类
[Table("SysInfo")] public partial class SysInfo { [Column("Id"), PrimaryKey] [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int? Id { get; set; } [Column("TypeName"), Nullable] public string TypeName { get; set; } [Column("InfoName"), Nullable] public string InfoName { get; set; } [Column("InfoValue"), Nullable] public string InfoValue { get; set; } [Column("CreateDate"), Nullable] public DateTime? CreateDate { get; set; } }
四、添加数据库访问上下文
public partial class SqliteDBContext : LinqToDB.Data.DataConnection { public SqliteDBContext(bool Password = false) : base("SQLite", "DataSource=" + AppDomain.CurrentDomain.BaseDirectory + "\\DB\\Data.db" + ";") { InitDataContext(); } public SqliteDBContext(string providerName, string configuration) : base(providerName, configuration) { InitDataContext(); } partial void InitDataContext(); public ITable<SysInfo> SysInfo { get { return this.GetTable<SysInfo>(); } } }
五、读取、插入、更新
[TestMethod] public void TestMethodRead() { try { SqliteDB.SqliteDBContext context = new SqliteDB.SqliteDBContext(); var first = context.SysInfo.First(); } catch (Exception ex) { throw ex; } }
[TestMethod] public void TestMethodInsert() { try { SqliteDB.SqliteDBContext context = new SqliteDB.SqliteDBContext(); SqliteDB.SysInfo info = new SqliteDB.SysInfo { Id = null, InfoName = "a", InfoValue = "值", TypeName = "分类" }; int i = context.Insert(info); } catch (Exception ex) { throw ex; } }
[TestMethod] public void TestMethodUpdate() { try { SqliteDB.SqliteDBContext context = new SqliteDB.SqliteDBContext(); SqliteDB.SysInfo info = context.SysInfo.Where(c => c.Id == 4).FirstOrDefault(); if (info != null) { info.InfoName = "测试更新"; } context.Update(info); } catch (Exception ex) { throw ex; } }
六、sqlite建表证句
CREATE TABLE SysInfo ( [Id] integer PRIMARY KEY autoincrement, -- 设置主键 [TypeName] varchar(50), [InfoName] varchar (50), [InfoValue] varchar (50), [CreateDate] datetime default (datetime(‘now‘, ‘localtime‘)) -- 时间 );
特别注意:由于主键是自增的,所以实体中的主键要允许为空 public int? Id { get; set; }
在新增数据的时候赋一个空值如下:
SqliteDB.SysInfo info = new SqliteDB.SysInfo { Id = null, InfoName = "a", InfoValue = "值", TypeName = "分类" };
Winform里添加SqliteSqlite数据库引用的步骤
标签:bsp void 数据库访问 insert current arc sed EDA ima
原文地址:https://www.cnblogs.com/wjx-blog/p/13077424.html