本文主要是介绍Sqlite检查表、字段是否存在,不存在则新增,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
有些时候我们可能需要在代码中检测某个表或某个表中某个字段是否存在,不存在的情况下通过代码去添加它,该怎么去判断呢 下边一块看一下:
判断表是否存在:
Sqlite会自动维护一个系统表sqlite_master,该表存储了我们所创建的各个table, view, trigger等信息。
select name from sqlite_master where type='table' order by name;
--select count(*) from sqlite_master where type='table' and name='表名'
判断字段是否存在:
这里有两种方式
第一种:可以清晰的查出表中的字段,在代码中用list接收然后判断list中有没有某个字段
PRAGMA table_info([tablename])
第二种:可以通过查询创建表时的sql语句中是否包含某个字段
select * from sqlite_master where type = 'table' and name = 'ACbio' and sql like '%Barcode%'
新增字段
其中的 column 可以省略,同时也可以不给 default 默认值。
alter table 表名 add column 'asdasd' varchar(20) default 'hahah'
--等同于alter table 表名 add 'asdasd' TEXT
代码操作
public (bool, string) CheckFieldPresenceOrNot(string TableName,string[] Field, DBConnHelper DB,string LocalDBPath) {using (IDbConnection db = DB.DBConnection("Sqlite", "", LocalDBPath, "")){try{string TableSql = $"select count(*) from sqlite_master where type='table' and name='{TableName}' ";int ExistTable= db.ExecuteScalar<int>(TableSql);if (ExistTable<1){//表不存在则新增表List<string> NeedAddField = new List<string>();for (int i = 0; i < Field.Length; i++){NeedAddField.Add($"{Field[i]} TEXT");}string FieldStr = string.Join(",", NeedAddField);string AddTableSql = $"create table {TableName}({FieldStr})";db.Execute(AddTableSql);string CreateAfter = $"select count(*) from sqlite_master where type='table' and name='{TableName}'";bool TableAddResult = db.ExecuteScalar<int>(TableSql)>0;if (!TableAddResult) return (false, $"添加本地库新表时失败,请联系管理员");else return (true, "");}List<string> FailureField = new List<string>();for (int i = 0; i < Field.Length; i++){string Sql = $"PRAGMA table_info({TableName})";List<TableStructureModel> TableStructure= db.Query<TableStructureModel>(Sql).ToList();bool Exist= TableStructure.Where(a=>a.name==Field[i]).ToList().Count()>0;if (!Exist){//如果不存在则新增字段string AddField = $"alter table {TableName} add column '{Field[i]}' TEXT";db.Execute(AddField)>0; //这里新增完之后应该判断一下是否新增成功//。。。。}} return (true,"");}catch (Exception ex){Log.Error($"检查新增本地数据表或库字段时失败:{ex.Message + ex.StackTrace + ex.InnerException}");return (false,ex.Message);}}}
这篇关于Sqlite检查表、字段是否存在,不存在则新增的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!