将多个数据库值添加到同一行的comboBox-如何
本文关键字:一行 如何 comboBox- 数据库 添加 | 更新日期: 2024-06-14 02:38:25
目前这段代码只显示数据库中"id"的值,我如何使它在同一行中同时显示"id"answers"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.使用参数化查询来避免SQL injection
攻击
2.调用MySqlDataReader
对象上的Read()
函数读取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();
}