目前这段代码只显示数据库中“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;
答案 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();
}