我无法将数据从sql添加到字符串列表中

时间:2015-05-20 06:27:44

标签: c# sql string

在这个程序中,我尝试将SQL中的数据转换为字符串列表,并在messageBox中显示它们。当我在textBox中输入一个字符时,程序应该开始搜索,并在查询中使用它,如下所示:

string sql = " SELECT * FROM general WHERE element='" + textBox1.Text + "'  OR element='" + textBox2.Text + "' OR element='" + textBox3.Text + "' OR element='" + textBox4.Text + "'";


        MySqlConnection con = new MySqlConnection("host=localhost;user=mate;password=1234;database=element_database");
        MySqlCommand cmd = new MySqlCommand(sql, con);
        con.Open();


        MySqlDataReader reader = cmd.ExecuteReader();
        string rd;
        rd = reader.ToString();

        int i=0;
        List<string>  item = new List<string>();


        while (reader.Read())
        {
            item.Add(rd["element"].ToString());//i got error in this line


        }

        for (i = 0; i < item.Count;i++ )
        {
            MessageBox.Show(item[i]);

        }

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你做错了什么?一堆东​​西:

在你的问题中,你写了一个错误,但没有告诉我们它是什么 例外有消息是有原因的:这样你就能知道出了什么问题。

关于你的代码:

  • 您正在将值连接到您的select语句,而不是使用parameterized queries.这为sql injection attacks.
  • 创建了一个空缺
  • 您在SqlConnection声明之外使用using 处理using个对象时,应始终使用IDisposable语句。
  • 您认为rd["element"]总是有值 如果它从数据库返回null,则在使用.ToString()时将获得空引用异常。正确的方法是将它的值放入局部变量,并在使用.ToString()方法之前检查此变量是否为空。
  • 您在代码中使用的是rd而不是readerrd变量没有意义,因为它只包含MySqlDataReader对象的字符串表示。

答案 1 :(得分:0)

您已将rd声明为字符串。您可能打算在此循环中使用reader对象:

while (reader.Read())
    {
        item.Add(reader["element"].ToString());// change "rd" to "reader"
    }

答案 2 :(得分:0)

我冒昧地修改SQL以使用IN而不是多个或语句,以及在查询中使用参数而不是基于字符串的方法。这应该可以解决你的问题。

    string elem1 = "@elem1";
    string elem2 = "@elem2";
    string elem3 = "@elem3";
    string elem4 = "@elem4";
    List<string> parameters = new List<string>{ elem1, elem2, elem3, elem4 };

    string sql = string.Format(" SELECT * FROM general WHERE element IN ({0})", string.Join(',', parameters.ToArray()));

    using(MySqlConnection con = new MySqlConnection("host=localhost;user=mate;password=1234;database=element_database"))
    {
        con.Open();
        MySqlCommand cmd = new MySqlCommand(sql, con);
        cmd.Parameters.AddWithValue(elem1, textBox1.Text);
        cmd.Parameters.AddWithValue(elem2, textBox2.Text);
        cmd.Parameters.AddWithValue(elem3, textBox3.Text);
        cmd.Parameters.AddWithValue(elem4, textBox4.Text);

        MySqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            string message = reader["element"] as string;
            if(!string.IsNullOrEmpty(message))
            {
                MessageBox.Show(message);
            }
        }
    }