嘿所有我正在寻找一种提取SQL查询字符串部分的简洁方法。
我的意思是:
说我有一个类似的查询:
https://myhost.com/cart/success?Authority=000000000000000000000000000000074139&Status=OK
我正在寻找将它们分成各自的部分(使用Dictionary作为存储每个值的两种方式):
SELECT
poc, event, network, vendor
FROM
bLine
WHERE
network = 'something'
AND
event = 'simple'
OR
event != 'hard'
ORDER BY
poc ASC
有人碰巧有类似的东西吗?我在SO上尝试了THIS示例,因为它似乎是我想要做的,但代码似乎不起作用:
有错误说:
错误CS0117'TokenInfo'不包含'Start'的定义
错误CS0117'TokenInfo'不包含'End'的定义
错误CS0117'TokenInfo'不包含'IsPairMatch'的定义
ETC等......
更新
似乎这个SO示例HERE完成了我需要它做的事情并且没有错误! :)
答案 0 :(得分:0)
如果你有一个固定的字符串,你可以使用这样的东西。这是我试图解决问题我可以说这不是最有效或最先进的方法,但它是一种方式这样做。
string[] Params = { "SELECT", "FROM", "WHERE", "AND", "OR", "ORDER BY" };
Dictionary<string, string> sqlSource = new Dictionary<string, string>();
string sqlString = "SELECT poc, event, network, vendor FROM bLine WHERE network = 'something'";
int i, j;
//iterate through all the items from Params array
for (i = 0; i < Params.Length; i++)
{
string result = "";
//take next element from Params array for SELECT next will be FROM
for (j = i + 1; j < Params.Length; j++)
{
int ab = sqlString.IndexOf(Params[j]);
//Get the substring between SELECT and FROM
if (ab > 0)
{
int pFrom = sqlString.IndexOf(Params[i]) + Params[i].Length;
int pTo = sqlString.LastIndexOf(Params[j]);
result = sqlString.Substring(pFrom, (pTo - pFrom));
}
//if there is a string then break the loop
if (result != "")
{
sqlSource.Add(Params[i], result);
break;
}
}
//if result is empty which is possible after FROM clause if there are no WHERE/AND/OR/ORDER BY then get substring between FROM and end of string
if (result == "")
{
int pFrom = sqlString.IndexOf(Params[i]) + Params[i].Length;
int pTo = sqlString.Length;
result = sqlString.Substring(pFrom, (pTo - pFrom));
sqlSource.Add(Params[i], result);
break;
}
}