在同一行的comboBox中添加多个数据库值 - 如何?

时间:2013-11-30 19:29:42

标签: c# mysql

目前这段代码只显示数据库中“id”的值,我该怎么做才能在同一行显示“id”和“name”值,比如“5-John Carpenter”?

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string constring = "datasource=localhost;port=3306;username=root;password=rootpassword";
        string Query = "select * from database2.employee where id='" + comboBox1.Text + "' ORDER BY Auto  ;";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        MySqlDataReader myReader;

1 个答案:

答案 0 :(得分:0)

1。使用参数化查询来避免SQL injection次攻击 2。Read()对象上调用MySqlDataReader函数来阅读select查询结果。
3。使用comboBox1.SelectedItem.ToString()代替ComboBox1.Text从组合框中获取所选项目。

试试这个:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string constring = "datasource=localhost;port=3306;username=root;password=rootpassword";
        string Query = "select * from database2.employee where id=@id ORDER BY Auto  ;";

        MySqlConnection conDataBase = new MySqlConnection(constring);            
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        cmdDataBase.Parameters.AddWithValue("@id",comboBox1.SelectedItem.ToString());
        MySqlDataReader myReader=cmdDataBase.ExecuteReader();
        if(myReader.Read())
       {
          TextBox1.Text=myReader["id"].ToString() +" - "+myReader["name"].ToString();
        }
      conDataBase.Close();
    }