1

我正在尝试编写具有 3 个文本框的代码,并且我需要将输入框中的信息传递给 SQL 数据库,然后将其显示在 gridview 中,用作购物车。我在我的 catch 块中不断收到一个错误,说我必须定义一个 @strItemName 的标量变量。这是我的代码...任何帮助将不胜感激。抱歉,如果此代码在网站上的格式不完全正确,这是我的第一篇文章。提前致谢。

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string strItemName = txtTitle.Text;
        string strMovieQuantity = txtNumMovies.Text;
        string strMoviePrice = txtPrice.Text;
        //string strCurrentUser = HttpContext.Current.User.Identity.Name;
        // I need this later to have a current user also inserted into the table



        string strConnection = ConfigurationManager.ConnectionStrings["cs3200"].ToString();
        SqlConnection myConnection = new SqlConnection(strConnection);

        string strSql = "INSERT INTO ShoppingCart ([ItemName], [QuantityOrdered], [UnitPrice]) VALUES  (@strItemName, @strQuantityOrdered, @strUnitPrice)";
        SqlCommand myCommand = new SqlCommand(strSql, myConnection);



        try
        {
            myConnection.Open();
            int intCnt = myCommand.ExecuteNonQuery();
            if (intCnt > 1)
            {
                lblInsert.Text = intCnt.ToString() + "Records was added";
            }
            else
            {
                lblInsert.Text = "One Record was inserted";
            }
            myConnection.Close();
        }


        catch (Exception ex)
        {
            lblInsert.Text = "Unable to insert your record" + "</br>";
            lblInsert.Text += "Error Message = " + ex.Message;
            myConnection.Close();
        }
4

2 回答 2

2

您必须在调用 ExecuteNonQuery() 方法之前指定参数。

 using(SqlConnection myConnection=new SqlConnection(cnStr))
   {
   using(SqlCommand myCommand=new SqlCommand(strSql,myConnection))
    {
    myCommand.Parameters.AddWithValue("@strItemName",value1);
    myCommand.Parameters.AddWithValue("@strQuantityOrdered",value2);
    myCommand.Parameters.AddWithValue("@strUnitPrice",value3);
    myConnection.Open();
    int intCnt = myCommand.ExecuteNonQuery();
    ....
    }
   }
于 2012-12-03T03:09:59.533 回答
0

如果您想使用“准备好的语句”(始终建议),您需要执行以下操作:

如果您只想要一个简单的“插入”,那么您可以执行以下操作:

string sql = 
  "insert into Region (RegionID, RegionDescription) values ('" + id +
  "', '" + desc + "')";
SqlCommand command = new SqlCommand(sql);
command.ExecuteNonQuery()
于 2012-12-03T03:12:33.380 回答