【问题标题】:Send Multiple Values to Mysql Query向 Mysql 查询发送多个值
【发布时间】:2016-09-14 18:28:12
【问题描述】:

这就是故事:

我有一个检查列表,其中包含我的数据库中的项目需要编写查询以仅获取所选项目的详细信息,然后将其填充到 gridviwe

 object[] items = checkedListBox1.CheckedItems.OfType<object>().ToArray();

        foreach (var item in items)
        {



            string connectionString = "server=127.0.0.1;uid=root;pwd=admin;database=per_update;";
            string query = "select * from tblcenters where centerName in('" + item + "')";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
                {
                    DataTable ds = new DataTable();
                    adapter.Fill(ds);


                    dataGridView1.DataSource = ds;
                }

} }

我编写了这段代码,它只为我提供了有关我选择的最后一个项目的详细信息。但我需要我选择的所有项目的详细信息

请不要担心在查询中不使用参数,因为这是一个示例

【问题讨论】:

  • 但是你应该总是使用参数来避免SQL注入
  • @BugFinder 。 . .然后解释 OP 如何为IN 列表使用参数。不幸的是,这是使用参数并不简单的情况之一。
  • item 是什么样的?我的意思是其中一个的内容
  • @rbr94 Yakkala, Maharagama,Malabe

标签: c# mysql sql checklistbox


【解决方案1】:

尝试构建您必须在 WHERE IN 语句中使用的字符串,如下所示:

var whereValues = "";

foreach (var item in items) {
    whereValues += ", '" + item + "'";
}

whereValues += whereValues.Substring(2, whereValues.Length-2);

string query = "select * from tblcenters where centerName in(" + whereValues + ")";

【讨论】:

  • 这适用于一些修正 whereValues += ", " + " ' " +item+ " ' " ;
  • 是的,如果您的值是字符串类型。我忘了考虑这一点。我编辑了我的帖子。
  • 我要补充一点,这个解决方案有两个潜在的错误。它还返回在 centerName 列中有空字符串的行,我希望你永远不会有嵌入引号的值。
  • @Steve 谢谢你的提示!因此,我将whereValues 的第一个字符截断并用string.Empty 而不是'' 初始化whereValues。我编辑了我的帖子。
【解决方案2】:
object[] items = checkedListBox1.CheckedItems.OfType<object>().ToArray();
string InStatement="("; //prepare the in clause
foreach (var item in items)
{
   InStatement+=item+",";

}
InStatement=InStatement.Substring(0, InStatement.Length - 1)+")";///trim last comma and add ending parenthesis
string connectionString = "server=127.0.0.1;uid=root;pwd=admin;database=per_update;";
string query = "select * from tblcenters where centerName in"+InStatement;
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
    using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
    {
      DataTable ds = new DataTable();
      adapter.Fill(ds);
      dataGridView1.DataSource = ds;
    }
}

【讨论】:

    【解决方案3】:

    您的问题是由循环内的项目值重置引起的。
    你说不需要使用参数,但是在这种情况下使用它们并没有太复杂并且具有更安全的代码

    // Get all the checked items in a list of strings...
    List<string> values = checkedListBox1.CheckedItems.Cast<string>().ToList();
    
    List<MySqlParameter> prms = new List<MySqlParameter>();
    List<string> prmsNames = new List<string>();
    
    // Loop over the values and build the parameter names and the parameters
    for (int x = 0; x < values.Count; x++)
    {
        // The parameter with a conventional name
        prms.Add(new MySqlParameter("@" + x.ToString(), MySqlDbType.VarChar) { Value = values[x] });
        // the parameter' names
        prmsNames.Add("@" + x.ToString());
    }
    
    // The command text
    string query = @"select * from tblcenters 
                     where centerName in (" + 
                    string.Join(",", prmsNames) + ")";
    
    using (MySqlConnection conn = new MySqlConnection(connectionString))
    using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
    {
        // Add the parameters collection to the select command....
        adapter.SelectCommand.Parameters.AddRange(prms.ToArray());
        DataTable ds = new DataTable();
        adapter.Fill(ds);
        dataGridView1.DataSource = ds;
    }
    

    【讨论】:

      【解决方案4】:

      更新。 也许你应该使用StringBuilder 来完成这项任务。此外,如果您对每个选定的项目进行请求,效率也会非常低。 类似以下的方法可能是更好的解决方案:

      StringBuilder sb = new StringBuilder();
      sb.Append("select * from tblcenters where centerName in(");
      for(int i=0;i<length;i++)
      {
        sb.Append('" + item[i] + "' + ",");
      }
      sb.Length--; // to get rid of the last comma (',')
      sb.Append(")");
      string query = sb.ToString();
      

      【讨论】:

      • 请使用问题中给出的陈述来证明您的目的。它可能会让一些用户感到困惑,因为它缺乏直接的上下文。
      • @rbr94 现在好点了吗?
      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多