4

如果我有一个字符串列表,即。List<String>,如何生成SQL语句,例如:

SELECT Column1 FROM Table1 WHERE Column1 IN ('String1','String2','String3')

'String1','String2','String3'的内容在哪里List<String>

没有 LINQ 等,因为我使用的是 VS2005。

4

9 回答 9

4

看看下面的版本

    [Test]
    public void Test()
    {
        var list = new List<string> {"String1", "String2", "String3"};
        string values = ArrayToString(list);
        string sql = string.Format("SELECT Column1 FROM Table1 WHERE Column1 IN ( {0} )", values);
    }

    private static string ArrayToString(IEnumerable<string> array)
    {
        var result = new StringBuilder();

        foreach (string element in array)
        {
            if (result.Length > 0)
            {
                result.Append(", ");
            }
            result.Append("'");
            result.Append(element);
            result.Append("'");
        }
        return result.ToString();
    }

结果声明SELECT Column1 FROM Table1 WHERE Column1 IN ( 'String1', 'String2', 'String3' )

于 2012-08-18T10:07:16.463 回答
0

要正确处理sql注入,更好的答案可能是使表单的查询......

select results.* from (
    select pk from table where column=value1 union
    select pk from table where column=value2 union
    select pk from table where column=value3 union
    select pk from table where column=value4 union
    select pk from table where column=value5
) filtered join table as results on filtered.pk = results.pk

然后让它对 c# 更友好

string items_filter = "";
int item_index=0;
OracleParameterCollection parameters = new OracleParameterCollection(); // Not sure what class to use here exactly, but just collect a bunch of stored procedure parameters

foreach (string item in list_of_items) {
    string item_name = string.Format("i_item{0}",item_index);  
    string item_sql = string.Format("select pk from table where column=:{0} union",item_name);
    parameters.Add(new Parameter("item_name",item));
    item_index+=1;  
}
if (items_filter.IsNullOrEmpty()) 
    return;

string sql = String.Format("select results.* from ({0}) filtered join table as results on filtered.pk = results.pk",items_filter);

OracleCommand c = new OracleCommand();
c.command = sql;
c.parameters = parameters;
c.execute();

或多或少。

于 2012-08-18T10:34:31.403 回答
0

不要为了防止 SQL 注入。

string sql_list = "";
foreach (string s in lst)
    sql_list+=string.Format("{0},",s.Replace("'","''"));
sql_list = string.Format("({0})",sql_list.substring(0,sql_list.length-2));

这可能对一些人有所帮助,并使用字符串生成器,或者不使用。

于 2012-08-18T10:18:30.507 回答
0

请不要使用到目前为止已提交的其他答案。它们无缘无故地包含 SQL 注入。

    List<String> strlist = new List<string>();
    strlist.Add("st1");
    strlist.Add("st2");
    strlist.Add("st3");

    var dynamicPart = string.Join(", ",
     Enumerable.Range(0, strlist.Count).Select(i => "@" + i).ToArray());
    for(i = 0 to strlist.Count)
     { /* add parameter to SqlCommand here with name ("@" + i) */ }
    string query = "SELECT Column1 FROM Table1 WHERE Column1 IN (" +
     dynamicPart + ")";

出于多种原因使用参数而不是文字(研究它们!)。

而不是使用笨拙的连接循环string.Join来为我们完成所有这些。

于 2012-08-18T10:14:38.373 回答
0
// Assume your list (List<string>) is named "myList"

// Please put the next line in an external string resource...
string selectStatement = "SELECT Column1 FROM Table1 WHERE Column1 IN ({0})";

StringBuilder stringBuilder = new StringBuilder("(");
foreach(string colName in myList)
    stringBuilder.Append(String.Format("'{0}',", colName));
stringBuilder.Append(")");

return String.Format(selectStatement, stringBuilder.ToString().Replace(",)", ")");
于 2012-08-21T10:21:42.903 回答
0
List<string> lst=new List<string>();lst.Add("Hello");lst.Add("Hello World");
string s="";
foreach(string l in lst)s+="\""+l+"\"";
s=Regex.Replace(s,"\"\"","\",\"");

string output="SELECT Column1 FROM Table1 WHERE Column1 ("+s+")";
于 2012-08-18T09:36:48.913 回答
0

尝试 :

        List<String> strlist = new List<string>();
        strlist.Add("st1");
        strlist.Add("st2");
        strlist.Add("st3");

        string query = "SELECT Column1 FROM Table1 WHERE Column1 IN (";

        for (int i = 0; i < strlist.Count; i++)
        {
            query += "\'" + strlist[i] + "\'" + (i == strlist.Count - 1 ? "" : ",");
        }

        query += ")";
于 2012-08-18T09:36:57.197 回答
0

由于您说它是内部操作,因此无需担心 SQL 注入,那么您可以通过此实现您想要的。

string str = "";

foreach(string s in list)
  str += "'" + s.Replace("'", "''") + "',";

str = str.SubString(0, str.Length - 1);

str = "SELECT Column1 FROM Table1 WHERE Column1 IN (" + str + ")";

//str will have your command ready.

我已经测试过了。它完美地工作。

于 2012-08-18T09:39:18.977 回答
0
List<string> items = new List<string>();
items.Add("string1");
items.Add("string2");
items.Add("string3");
string AllItems = "";
foreach (string item in items)
{
    AllItems += string.Format("\"{0}\",",item);
}
AllItems = AllItems.TrimEnd(',');
string YourSQLQuery = string.Format("SELECT Column1 FROM Table1 WHERE Column1 IN ({0})", AllItems);
MessageBox.Show(YourSQLQuery);
于 2012-08-18T09:39:40.450 回答