如何从List生成SQL语句?

时间:2012-08-18 09:27:05

标签: c# sql list visual-studio-2005

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

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

其中'String1','String2','String3'List<String>的内容?

没有LINQ等,因为我正在使用VS2005。

9 个答案:

答案 0 :(得分: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' )

答案 1 :(得分: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+")";

答案 2 :(得分: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 += ")";

答案 3 :(得分: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.

我测试了它。它运作得很好。

答案 4 :(得分: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);

答案 5 :(得分: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,它为我们做了所有这些。

答案 6 :(得分: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));

可能对某些人有所帮助,并使用字符串生成器。

答案 7 :(得分: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

然后让它变得更友好

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();

或多或少。

答案 8 :(得分: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(",)", ")");