设为首页 加入收藏

TOP

巧用C# Split()函数获取SQL语句中操作字段(一)
2014-11-23 17:56:09 来源: 作者: 【 】 浏览:82
Tags:巧用 Split 函数 获取 SQL 语句 操作

这是前天工作时要求的,将SQL语句的操作字段获取出来挂在树节点上,感觉这个函数以后还有可能会用到,特此总结一下,函数中没有实现Select *的操作,只要添加判断条件即可。


工具函数:Split()函数:通过字符分割字符串为一个string类型的一维数组。


String.Split 方法有6个重载函数:
1) public string[] Split(params char[] separator) 返回的字符串数组包含此实例中的子字符串
2) public string[] Split(char[] separator, int count) 返回的字符串数组包含此实例中的子字符串。 参数指定返回的子字符串的最大个数。
3) public string[] Split(char[] separator, StringSplitOptions options) 返回的字符串数组包含此字符串中的子字符串。 参数指定是否返回空数组元素。
4) public string[] Split(string[] separator, StringSplitOptions options) 返回的字符串数组包含此字符串中的子字符串。 参数指定是否返回空数组元素。
5) public string[] Split(char[] separator, int count, StringSplitOptions options) 返回的字符串数组包含此字符串中的子字符串(由指定 Unicode 字符数组的元素分隔)。 参数指定要返回子字符串的最大数量,以及是否返回空数组元素。
6) public string[] Split(string[] separator, int count, StringSplitOptions options)
返回的字符串数组包含此字符串中的子字符串(由指定字符串数组的元素分隔)。 参数指定要返回子字符串的最大数量,以及是否返回空数组元素。


注:
StringSplitOptions 为一个枚举类型,有两个成员:(1)None:返回值包括含有空字符串的数组元素;(2)RemoveEmptyEntries:返回值不包括含有空字符串的数组元素 。具体例子可到网上找相关代码。
思路:将字符串通过Split()函数进行分割为字符串数组,然后对字符串数据进行判断即可。


效果:



代码:


///


/// 获取查询字段代码
///

///
///
private string GetSQLOperateField(string sOperationSQL)
{
if (string.IsNullOrEmpty(sOperationSQL))
{
return string.Empty;
}


string sAppendNodeText = string.Empty;
sOperationSQL = sOperationSQL.Trim();
string[] strList = null;
string sKey = sOperationSQL.Substring(0, 6);
switch (sKey.ToUpper())
{
case "SELECT":
{
strList = sOperationSQL.Split(new char[2] { ' ', ',' });
for (int i = 1; i < strList.Length; i++)
{
if (strList[i].ToUpper().Equals("FROM"))
{
break;
}


if (!string.IsNullOrEmpty(strList[i]))
{
sAppendNodeText += strList[i] + ",";
}
}


if (sAppendNodeText.Length > 1)
{
sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
}
sAppendNodeText = "SELECT【" + sAppendNodeText + "】";
break;
}
case "INSERT":
{
strList = sOperationSQL.Trim().Split(new char[5] { ' ', ',', '(', ')', '\'' });
for (int i = 0; i < strList.Length; i++)
{
if (strList[i].ToUpper().Equals("WHERE"))
{
break;
}


if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=") > -1 && strList[i].Length > 1)
{
int iIndex = strList[i].IndexOf("=");
if (iIndex > 0)
{
sAppendNodeText += strList[i].Substring(0, iIndex) + ",";
}
}


if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=", 0, 1) > -1)
{
sAppendNodeText += strList[i - 1] + ",";
}
}


if (sAppendNodeText.Length > 1)
{
sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
}


sAppendNodeText = "INSERT【" + sAppendNodeText + "】";
break;
}
case "UPDATE":
{
strList = sOperationSQL.Tri

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Ember.js创建简单的Todo应用 下一篇C#之自定义的implicit和explicit..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: