遇到string.Replace/Regex.Replace有问题

Lat*_*san 0 c# string

我有这样的SQL查询:

UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);
Run Code Online (Sandbox Code Playgroud)

此查询是动态生成的.我想要做的是通过一个函数运行它,它将有效地用@pN相应的值替换所有参数.

我试图用标准做到这一点,string.ReplaceRegex.Replace没有运气 - 替换没有发生.

这是我到目前为止所尝试的:

class Program
{
    static string _lastQuery;

    static void Main(string[] args)
    {
        var sqlQuery = "UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);";
        var sqlParamters = new Dictionary<string, object>()
        {
            { "@p0", 12345 },
            { "@p1", 65432 }
        };

        LogLastQuery(sqlQuery, sqlParamters);
    }

    static void LogLastQuery(string sqlQuery, Dictionary<string, object> sqlParamters = null)
    {
        _lastQuery = sqlQuery;
        if (sqlParamters != null && sqlParamters.Count > 0)
            foreach (KeyValuePair<string, object> sqlParamter in sqlParamters)
                _lastQuery = Regex.Replace(
                    _lastQuery, 
                    "\\@" + sqlParamter.Key,
                    sqlParamter.Value.GetType() == typeof(int) || sqlParamter.Value.GetType() == typeof(decimal)
                        ? sqlParamter.Value.ToString() 
                        : "'" + sqlParamter.Value.ToString() + "'");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望函数执行参数替换,理想情况下输出如下内容:

UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (12345,65432);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?


更新

我用的是sqlQuerysqlParamters同样的用户un-lucky已经显示出,即

{
    mySqlCommand.Parameters.AddWithValue(sqlParamter .Key, sqlParamter.Value);
}
Run Code Online (Sandbox Code Playgroud)

事实证明,我一直在生成没有的字典密钥@,.NET已经自动为我添加它们(当它们丢失时 - 如用户所解释的那样juharr).

有时,我会动态生成sql查询和参数 - 其中键列表及其对应值是在for/ foreachloop 中生成的.这导致了混合使用的情况.

所以,为了解决这个问题 - 我已经像这样更新了我的功能,它按预期工作:

internal void LogLastQuery(string sqlQuery, Dictionary<string, object> sqlParamters = null)
{
    _lastQuery = sqlQuery;
    if (sqlParamters != null && sqlParamters.Count > 0)
        foreach (KeyValuePair<string, object> sqlParamter in sqlParamters)
            _lastQuery = Regex.Replace(
                _lastQuery,
                (sqlParamter.Key.ToString()[0] != '@' ? "\\@" : "") + sqlParamter.Key,
                sqlParamter.Value.GetType() == typeof(int) || sqlParamter.Value.GetType() == typeof(decimal)
                    ? sqlParamter.Value.ToString()
                    : "'" + sqlParamter.Value.ToString() + "'");
}
Run Code Online (Sandbox Code Playgroud)

现在处理这两种情况.我不确定这是否是最好的方法,但它现在工作正常.

小智 6

您在词典中的键已经有"@"符号,请尝试使用sqlParamter.Key而不是"\\@" + sqlParamter.Key.