在LIKE语句中插入参数化值

时间:2013-04-03 14:03:43

标签: c# mysql .net mono

我有一个方法可以更新mysql数据库中的记录,只需在字符串中使用时,查询就可以正常工作:

string query = @"UPDATE Batches SET `State`=@State, `PostDocCount`=@PostDocCount WHERE `FilePath` LIKE '%MYDIRECTORYSTRING%'";

虽然如果我用参数化查询替换MYDIRECTORYSTRING,例如:

string query = @"UPDATE Batches SET `State`=@State, `PostDocCount`=@PostDocCount WHERE `FilePath` LIKE '%@dirName%'";

它不再有效(记录未更新) - 我也确认了@dirName == MYDIRECTORYSTRING。所以我被引导相信这是一个语法问题? (虽然两个查询似乎都执行正常..)

以下是我的完整方法:

 public void UpdateBatch(string postDocCount, string dirName, string state)
        {
        string query = @"UPDATE Batches SET `State`=@State, `PostDocCount`=@PostDocCount WHERE `FilePath` LIKE '%@dirName%'";

        //Open connection
        if (this.OpenConnection() == true)
        {
            //create mysql command
            MySqlCommand cmd = new MySqlCommand();
            //Assign the query using CommandText
            cmd.CommandText = query;
            //Assign the connection using Connection
            cmd.Connection = connection;

            // Parametized queries 
            cmd.Parameters.AddWithValue("@PostDocCount", postDocCount);
            cmd.Parameters.AddWithValue("@State", state);
            cmd.Parameters.AddWithValue("@dirName", dirName);

            //Execute query
            cmd.ExecuteNonQuery();

            //close connection
            this.CloseConnection();
        }
    }

1 个答案:

答案 0 :(得分:1)

在将dirName变量分配给"@dirName"参数之前,您应该合并%通配符

dirName = "%" + dirName + "%";

然后将您的sql文本更改为

string query = @"UPDATE Batches SET `State`=@State, `PostDocCount`=@PostDocCount " + 
                "WHERE `FilePath` LIKE @dirName";