有些时候我们可能需要在代码中检测某个表或某个表中某个字段是否存在,不存在的情况下通过代码去添加它,该怎么去判断呢 下边一块看一下:

判断表是否存在:

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(TableSql);

if (ExistTable<1)

{//表不存在则新增表

List NeedAddField = new List();

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(TableSql)>0;

if (!TableAddResult) return (false, $"添加本地库新表时失败,请联系管理员");

else return (true, "");

}

List FailureField = new List();

for (int i = 0; i < Field.Length; i++)

{

string Sql = $"PRAGMA table_info({TableName})";

List TableStructure= db.Query(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);

}

}

}

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: