string menuRecipe = "SELECT * FROM recipelist WHERE menu_ID = '" + menuID + "'";
MySqlCommand recipeCmd = new MySqlCommand(menuRecipe, db.mycon);
MySqlDataReader recipeDr = recipeCmd.ExecuteReader();
string[] info = new string[8];
while (recipeDr.Read())
{
info[1] = (recipeDr["recipe_ID"].ToString());
info[2] = (recipeDr["stock_ID"].ToString());
info[4] = (recipeDr["recipe_quantity"].ToString());
string stockName = "SELECT stock_name FROM stocksdb WHERE stock_ID = '" + info[2] + "'";
cmd = new MySqlCommand(stockName, db.mycon);
MySqlDataReader nameDr = cmd.ExecuteReader();
while (nameDr.Read())
{
info[3] = (nameDr["stock_name"].ToString());
}
this.recipeList.Items.Add(new ListViewItem(new string[] { info[1], info[2], info[3], info[4] }));
}
我主要想减少必须使用多个SQL命令字符串,虽然我不知道如何以及如何将它们分隔到各自的位置,因为有些可能会混乱。
答案 0 :(得分:5)
您可以将查询更改为
SELECT r.*, s.stock_name FROM recipelist r
LEFT OUTER JOIN stocksdb s ON r.stock_ID = s.stock_ID
WHERE menu_ID = @parameter
答案 1 :(得分:2)
您可以在初始查询中执行INNER JOIN,以将stocksdb表链接到stock_ID上的食谱列表表。
答案 2 :(得分:2)
我会将您的代码更改为以下内容:
string connect = "...";
using (var cn = new SqlConnection(connect))
{
cn.Open();
string sql = @"
SELECT r.*, s.stock_name
FROM recipelist r
LEFT OUTER JOIN stocksdb s ON r.stock_ID = s.stock_ID
WHERE menu_ID = @MenuID";
var cmd = new SqlCommand(sql, cn);
cmd.Parameters.Add("@MenuID", SqlDbType.Int).Value = menuID;
var dr = cmd.ExecuteReader();
while (dr.Read())
{
this.recipeList.Items.Add(new ListViewItem(new string[] {
dr["recipe_ID"].ToString(),
dr["stock_ID"].ToString(),
dr["stock_name"].ToString(),
dr["recipe_quantity"].ToString()
}));
}
}