2
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 命令字符串,尽管我不知道如何以及如何将它们隔离到各自的位置,因为有些可能会混乱。

4

3 回答 3

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
于 2012-12-20T03:22:30.120 回答
2

您可以在初始查询中执行 INNER JOIN 以将 stockdb 表链接到 stock_ID 上的配方列表表。

于 2012-12-20T03:19:03.873 回答
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()
        }));
    }
}
于 2012-12-20T03:37:27.587 回答