简体   繁体   English

遇到string.Replace / Regex.Replace问题

[英]Having trouble with string.Replace / Regex.Replace

I have a sql query like this: 我有一个这样的SQL查询:

UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);

This query is dynamically generated. 该查询是动态生成的。 What I want to do is run it through a function, which will effectively replace all the @pN parameters with their corresponding values. 我想做的是通过一个函数运行它,该函数将有效地将所有@pN参数替换为其相应的值。

I have tried to do this with standard string.Replace as well as Regex.Replace with no luck - the replace is not taking place. 我试图用标准的string.Replace以及Regex.Replace做到这一点,但运气不好-替换没有发生。

This is what I tried so far: 这是我到目前为止尝试过的:

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() + "'");
    }
}

I want the function to do the parameter replace and ideally output something like this: 我希望函数执行参数替换并理想地输出如下内容:

UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (12345,65432);

Any ideas? 有任何想法吗?


Update 更新资料

I use the sqlQuery and sqlParamters just as user un-lucky has shown, ie 我使用sqlQuerysqlParamters就像用户un-lucky已经显示出,即

{
    mySqlCommand.Parameters.AddWithValue(sqlParamter .Key, sqlParamter.Value);
}

It turns out, I have been generating the dictionary keys without the @ and .NET has been automatically adding them for me (when they are missing - as explained by user juharr ). 事实证明,我一直在生成没有@的字典键,并且.NET已自动为我添加它们(当它们丢失时-如用户juharr )。

Sometimes, I generate the sql query and parameters dynamically - where the list of keys and their corresponding values were generated in a for / foreach loop. 有时,我会动态生成sql查询和参数-在for / foreach循环中生成键列表及其对应的值。 This resulted in a case of mix usage going on. 这样就导致了混合使用的情况。

So, to handle this - I've updated my function like this and it's working as intended: 因此,为了解决这个问题-我已经像这样更新了我的函数,它可以按预期工作:

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() + "'");
}

This now deals with both cases. 现在处理这两种情况。 I am not sure if this is the best method, but it works fine for now. 我不确定这是否是最好的方法,但目前效果很好。

您在字典中的键已经有“ @”符号,请尝试使用sqlParamter.Key代替"\\\\@" + sqlParamter.Key

I think its better to create SqlCommand with that query and add those values as parameters will be the best option for you to execute the query, instead for replacement; 我认为最好使用该查询创建SqlCommand并将这些值添加为参数,这将是您执行查询的最佳选择,而不是替换。 which means you can try something like this: 这意味着您可以尝试如下操作:

 var sqlQuery = "UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);";
 var sqlParamters = new Dictionary<string, object>()
 {
      { "@p0", 12345 },
      { "@p1", 65432 }
 };
 SqlCommand mySqlCommand = new SqlCommand(sqlQuery , conSQL); // conSQL is the connection
 foreach (KeyValuePair<string, object> sqlParamter in sqlParamters)
 {
    mySqlCommand.Parameters.AddWithValue(sqlParamter .Key, sqlParamter.Value);
 }
 mySqlCommand .ExecuteNonQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM