0

我的输出查询如下所示:

select * from Calls where CallerID = "User.Name" and Endpoint in ("C,D,V") order by JoinTime desc;

我的带有参数的 C# 查询字符串如下所示:

string SQLQuery = "select * from Calls where CallerID = @UserName and EndpointType in ({0}) order by JoinTime desc";

添加参数的代码如下所示:

...

string[] Endpoints = new string[] {"C","D","V"}; //EXAMPLE string array
string UserNameStr = "User.Name"; //EXAMPLE string UserNameStr value

...

string[] paramNames = Endpoints.Select((s, i) => "@endpoint" + i.ToString()).ToArray();

string inClause = string.Join(",", paramNames);


using (cmd = new MySqlCommand((string.Format(SQL, inClause)),connection))
{
    for (int i = 0; i < paramNames.Length; i++)
    {
        cmd.Parameters.AddWithValue(paramNames[i], Endpoints[i]);
    }
}

cmd.Parameters.Add("@UserName", MySqlDbType.String).Value = UserNameStr;

MySqlDataReader dataReader = cmd.ExecuteReader(); 

...

但是,如果我想添加另一个 IN 运算符,那么输出查询将如下所示;

select * from Calls where CallerID = "User.Name" and Endpoint in ("C","D","V") and ConferenceCall in ("D","C") order by JoinTime desc;

我怎么做?Linq 中是否有一些可以使用的功能?

4

1 回答 1

0

与第一次相同的方式:

// endpoints = comma-delimited list of endpoints
// conferenceCalls = comma-delimited list of conference calls

string SQLQuery = "select * from Calls " + 
                  "where CallerID = @UserName and " + 
                  "EndpointType in ({0}) and " + 
                  "ConferenceCall in ({1}) " + 
                  "order by JoinTime desc";

cmd = new MySqlCommand((string.Format(SQL, endpoints, conferenceCalls)),connection);

如评论中所述,请非常小心地验证字符串以避免 SQL 注入攻击。没有直接的方法将集合作为 SQL 参数传递。有很多方法可以做到这一点(传递分隔字符串并解析它是我见过的最常见的方法),但如果您可以控制设置值并验证数据,那么您应该没问题。

于 2013-03-01T22:15:20.537 回答