-2

我有一个方法可以更新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();
        }
    }
4

1 回答 1

1

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

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

然后将您的 sql 文本更改为

string query = @"UPDATE Batches SET `State`=@State, `PostDocCount`=@PostDocCount " + 
                "WHERE `FilePath` LIKE @dirName";
于 2013-04-03T14:06:49.037 回答