首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c#从字符串中提取sql查询部分

c#从字符串中提取sql查询部分
EN

Stack Overflow用户
提问于 2018-06-07 22:45:09
回答 1查看 600关注 0票数 0

嘿,所有我正在寻找一种干净的方式来提取我的SQL查询字符串的部分。

我的意思是:

假设我有这样一个查询:

代码语言:javascript
复制
SELECT 
    poc, event, network, vendor 
FROM 
    bLine 
WHERE 
    network = 'something' 
AND 
    event = 'simple' 
OR 
    event != 'hard' 
ORDER BY 
    poc ASC

我正在寻找在它自己的部分中划分每个值(使用字典作为存储每个值的一种方式):

代码语言:javascript
复制
Key      |Value
-------------------------------------
SELECT   |poc, event, network, vendor
FROM     |bLine
WHERE    |network = 'something' 
AND      |event = 'simple' 
OR       |event != 'hard' 
ORDER BY |poc 
??       |ASC

有人碰巧已经有这样的东西了吗?我已经尝试了THIS示例,因为它似乎是我想要做的,但代码似乎不起作用:

错误信息显示:

错误CS0117 'TokenInfo‘不包含'Start’的定义

错误CS0117 'TokenInfo‘不包含'End’的定义

错误CS0117 'TokenInfo‘不包含'IsPairMatch’的定义

等等……

更新

看起来这个示例HERE做了我需要它做的事情,并且没有错误!:)

EN

回答 1

Stack Overflow用户

发布于 2018-06-08 02:48:53

如果你总是有一个固定的字符串,你可以使用像this.This这样的东西来解决问题,我可以说这不是最有效或高级的方法,但这是一种方法。

代码语言:javascript
复制
        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;
            }

        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50744148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档