在c#的查询中添加参数

时间:2015-08-04 12:51:14

标签: c# mysql sql parameters

在aspx页面后面的代码中,我在sql查询中传递Parameters上的值时遇到问题。

我使用的是MySql数据库。

第1步:

我在列表中添加查询的输出:

while (reader.Read())
{
    idcolor = reader["idcolor"].ToString();
    colorList.Add(idcolor.ToString());
}

ns = string.Join("','", colorList.ToArray());

调试中,输出为:

ns = red','green

第2步:

我需要在SQL查询中使用string ns的值。

并传递string nsparameters的值:

str = null;
str = ns == null ? "" : ns.ToString();

sql = @" SELECT * FROM Experience WHERE Colors IN (?); ";

    DataSet dsColors = new DataSet();

    using (OdbcConnection cn =
      new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        cn.Open();

        using (OdbcCommand cmd = new OdbcCommand(sql, cn))
        {

            cmd.Parameters.AddWithValue("param1", Server.UrlDecode(str.ToString()));

            OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
            adapter.Fill(dsColors);
        }
    }

    return dsColors;

第3步:

如果在查询中使用:

sql = @" SELECT * FROM Experience WHERE Colors IN (?); ";

dataset中的输出为空。

如果在查询中使用:

sql = @" SELECT * FROM Experience WHERE Colors IN ( '" + Server.UrlDecode(str.ToString()) + "' ); ";

dataset中的输出是正确的。

有人知道如何解决这个问题?

你能建议吗?

你能帮助我吗?

提前谢谢。

4 个答案:

答案 0 :(得分:1)

你必须使用MySql.Data.MySqlClient;连接到Mysql:

sql = @" SELECT * FROM Experience WHERE Colors IN (@param1,@param2) ";

    DataSet dsColors = new DataSet();

    using ( MySqlConnection cn =
      new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        cn.Open();

        using (MySqlCommand cmd = new MySqlCommand(sql, cn))
        {

            cmd.Parameters.Add("@param1", colorList[0]/ToString());
            cmd.Parameters.Add("@param2",colorList[1].ToString());    
            MySqlDataAdapter adapter = new MySqlaAdapter(cmd);
            adapter.Fill(dsColors);
        }
    }

答案 1 :(得分:1)

如果您不想为每种颜色添加参数,可以使用

MySql.Data.MySqlClient.MySqlHelper.EscapeString()

这不是很漂亮,但参数内部使用它,您可以添加动态数量的值,并且您可以安全地防止注射

while (reader.Read())
{
    idcolor = reader["idcolor"].ToString();
    colorList.Add(MySql.Data.MySqlClient.MySqlHelper.EscapeString(idcolor));
}

ns = string.Join("','", colorList.ToArray());

答案 2 :(得分:0)

您看起来与上下文关闭,但尝试一次获取一种颜色的结果,并继续更改参数的VALUE。通过调用FILL,它将在每次调用时不断向表中添加记录。但是,将FILL设置为指向DataTable而不是DataSet。因此它不会继续将TABLES放入您的数据集中,而是使用继续附加到它的数据集。如果您有1种颜色或1000种颜色,这将有效...

... rest of previous code BEFORE the OdbcCommand
... and ensure clean values for your colors as others have noted.
using (OdbcCommand cmd = new OdbcCommand(sql, cn))
{
   // Just to add the parameter "place-holder" for your query
   cmd.Parameters.AddWithValue("param1", "");

   // DataTable ONCE to receive all the colors being queried
   DataTable tblAllColors = new DataTable();

   // build the adapter ONCE no matter how many colors you will be querying
   OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);

   // so for this loop, you are just getting the colors one at a time.
   foreach( string s in colorList )
   {
      // next color you are trying to get... just overwrite the 
      // single parameter with the new color.
      adapter.SelectCommand.Parameters[0].Value = s;
      adapter.Fill(tblAllColors);
   }

   // you would otherwise have to build your query dynamically and keep 
   // adding parameter-placeholders "?" for each color in a comma list 
   // as you were attempting... which would be a slightly different query.
}

dsColors.Tables.Add( tblAllColors );

答案 3 :(得分:0)

您需要为in子句中的每个项目添加参数和占位符。例如

sql = @" SELECT * FROM Experience WHERE Colors IN (?,?,?); ";

然后为每一个添加参数。

cmd.Parameters.AddWithValue("param1", Server.UrlDecode(str.ToString()));

示例

        List<string> colours = new List<string>();

        colours.Add("black");
        colours.Add("red");

        var placeHolders = string.Join(",",(from colour in colours select "?").ToList());

        var sql = @String.Format(" SELECT * FROM Experience WHERE Colors IN ({0}); ",placeHolders);

        DataSet dsColors = new DataSet();

        using (OdbcConnection cn = new OdbcConnection(ConnectionString))
        {
            cn.Open();

            using (OdbcCommand cmd = new OdbcCommand(sql, cn))
            {
                foreach(var colour in colours)
                {
                    cmd.Parameters.AddWithValue(colour, colour);
                }

                OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
                adapter.Fill(dsColors);
            }
        }