我想在表单加载中获取我的数据库中的多个数据。但我发现代码很长而且重复。有人可以让这段代码更短一点吗?
这是我的代码
private void Form1_Load(object sender, EventArgs e)
{
string a = label1.Text;
string connString = "Server=Localhost;Database=this;Uid=root;password=root";
using (var connection = new MySqlConnection(connString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
command.Parameters.AddWithValue("?room", a);
command.ExecuteNonQuery();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button1.Text = reader["Room_name"].ToString();
}
}
}
string b = label2.Text;
string connString2 = "Server=Localhost;Database=this;Uid=root;password=root";
using (var connection = new MySqlConnection(connString2))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
command.Parameters.AddWithValue("?room", b);
command.ExecuteNonQuery();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button2.Text = reader["Room_name"].ToString();
}
}
}
}