如何获取标签内的值并将其用作SQL where子句中的条件?

时间:2013-12-04 16:22:20

标签: c# wpf

下面是我的代码,我尝试过ToString(),但是在运行代码时会出现错误。我想用“newName”作为我的条件来展示我需要的东西。任何帮助,将不胜感激。

void onFoodLoad() {
        SqlConnection conn = new SqlConnection(dbConn);
        SqlCommand cmd;
        String connStr;
        string newName = name.Content.ToString();

        try {
            conn.Open();
            //problem here
            connStr = "Select Ingredients, Directions From Food where FoodName = @newFoodName";

            cmd = new SqlCommand(connStr, conn);
            cmd.Parameters.AddWithValue("@nnewFoodName", SqlDbType.NVarChar);
            cmd.Parameters["@newFoodName"].Value = newName;
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                //name.Content = reader["FoodName"];
                ingredient.Content = reader["Ingredients"];
                direction.Content = "Directions "+ reader["Directions"];
            }
            conn.Close();
        }
        catch(Exception ex){
            MessageBox.Show(ex.Message);
        }


    }

1 个答案:

答案 0 :(得分:0)

connStr更改为:

connStr = "Select Ingredients, Directions From Food where FoodName = @NewFoodName";

并添加:

cmd.Parameters.AddWithValue("@NewFoodName", newName);
创建SqlCommand

一种副作用,但你绝对应该将你的Sql*创作包裹在using块中,以便在你完成它之后得到妥善处理,除非你正确处理你自己。