首页 > 解决方案 > 如何将 command.Parameters.AddWithValue 与值一起使用?

问题描述

我的代码如下:

if (!string.IsNullOrEmpty(Mpdue.TheObjectPropertyNameNs))
{

    string sql = @String.Format(" SELECT * FROM doTable WHERE dOCode IN ('" + Mpdue.TheObjectPropertyNameNs + "'); ");

    using (OdbcConnection myConnectionString =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        using (OdbcCommand command =
            new OdbcCommand(sql, myConnectionString))
        {
            try
            {
                command.Connection.Open();

                using (OdbcDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Response.Write(reader["dOCode"].ToString() + "<br />");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
 }

输出:

D410
D420
D430
D440

现在我尝试command.Parameters.AddWithValueMySql查询中使用。

我一直在尝试找不到错误,使用时输出command.Parameters.AddWithValue为空,为什么?

if (!string.IsNullOrEmpty(Mpdue.TheObjectPropertyNameNs))
{

    string sql = @String.Format(" SELECT * FROM doTable WHERE dOCode IN (?); ");

    using (OdbcConnection myConnectionString =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        using (OdbcCommand command =
            new OdbcCommand(sql, myConnectionString))
        {
            try
            {
                command.Connection.Open();
                command.Parameters.AddWithValue("param1", Mpdue.TheObjectPropertyNameNs);

                using (OdbcDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Response.Write(reader["dOCode"].ToString() + "<br />");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

编辑#2

var parameters = new string[Mpdue.TheObjectPropertyNameNs.Length];
var paramValue = string.Join(", ", parameters);


string sql = string.Format("SELECT * FROM doTable WHERE dOCode IN ({0})", string.Join(", ", parameters.Select(x => "?")));

int index = 0;
foreach (var param in parameters)
{
   command.Parameters.AddWithValue("param{index}", param);
   index++;
}

编辑#1

我的新代码如下:

if (!string.IsNullOrEmpty(Mpdue.TheObjectPropertyNameNs))
{
   var parameters = new string[Mpdue.TheObjectPropertyNameNs.Length]; 

   string sql = @String.Format(" SELECT * FROM doTable WHERE dOCode IN ({0})", string.Join(", ", parameters));

        using (OdbcConnection myConnectionString =
            new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
        {
            using (OdbcCommand command =
                new OdbcCommand(sql, myConnectionString))
            {
                try
                {
                    command.Connection.Open();

                    for (int i = 0; i < Mpdue.TheObjectPropertyNameNs.TrimStart('\'').TrimEnd('\'').Length; i++)
                    {
                       parameters[i] = string.Format("param1{0}", i);
                       command.Parameters.AddWithValue(parameters[i], Mpdue.TheObjectPropertyNameNs.TrimStart('\'').TrimEnd('\'')[i]);
                    }                    

                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Response.Write(reader["dOCode"].ToString() + "<br />");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("operation failed!", ex);
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
     }

错误 :

ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.24-log]您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ' , , , , , , , , , , , , , , , , , , , , , , , , , ) 附近使用正确的语法

标签: c#mysql

解决方案


为了解决这个问题,您可以将查询更改为以下字符串:

SELECT * FROM doTable WHERE FIND_IN_SET(dOCode, ?)

然后,您需要确保您的参数设置在表单中D410, D420, D430, D440。所以你可以像第一种方法一样构建它

var paramValue = string.Join(", ", parameters);

稍后添加

command.Parameters.AddWithValue("param1", paramValue);

请注意,使用FIND_IN_SET可能会对性能产生负面影响,因为它会扫描整个表而不管索引如何。另一种方法是将 n 个参数插入到查询中,然后单独添加每个参数,例如

string sql = string.Format("SELECT * FROM doTable WHERE dOCode IN ({0})", string.Join(", ", parameters.Select(x => "?")));
// ...
int index = 0;
foreach(var param in parameters)
{
  command.Parameters.AddWithValue($"param{index}", param);
  index++;
}

如果预期的参数数量不太高,这是一种可行的方法。


推荐阅读