C# 中 SQLite 查询数据库表中字段(列)是否存在的方法

查询SQLite数据库表中字段(列)存在的方法

使用SQL语句为:PRAGMA table_info([DeviceTrees]);   其中“DeviceTrees”为数据库表的名称。

使用SQLite Expert Professional工具,查看该语句是否起作用,这里使用的版本是v3.1.9的。

输入语句后,点击“Execute SQL”按钮后,查询结果如下图所示,说明该语句查询是正确的。

在C# 中通过该语句查询DeviceTrees表中所有字段(列),放入DataTable中,通过循环判读字段(列)是否存在。示例代码如下所示

public  bool InsertColumnGuidFunc()
{
	bool isExist = false;
	try
	{
		List<string> columnList = new List<string>();
		//查询DetectorTrees 表信息
		string strSql = "PRAGMA table_info([DeviceTrees]);";
        //调用SQLite数据库接口
		using (DataTable dt = SQLiteDbHelper.ExecuteDataTable(strSql.ToString(), null))
		{
			if (dt != null && dt.Rows.Count > 0)
			{
				for (int i = 0; i < dt.Rows.Count; i++)
				{
					string columnName = dt.Rows[i]["name"].ToString();
					columnList.Add(columnName);
				}
			}
		}
		//判断列是否存在
		if (columnList != null && columnList.Count > 0)
		{
			if (columnList.Contains("DeviceGuid"))
				isExist = true;
			else
				isExist = false;
		}
	}
	catch (Exception ex)
	{

	}
	finally
	{

	}

	return isExist;
}

根据查询结果,如果字段(列)存在,则不进行插入字段(列)的操作,反之,则可通过sql语句向表中插入想要的字段(列)。

扩展

插入字段(列)主要语句为:

alter table DeviceTrees add column [DeviceGuid] VARCHAR(100) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000');

**************************************************************************************************************

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值