2012-12-03 6 views
1

3 개의 텍스트 상자가있는 코드를 작성하려고하는데 상자에 입력 된 정보가 필요하므로 SQL 데이터베이스로 전달해야합니다. 장바구니 기능을하는 그리드 뷰. catch 블록에서 @strItemName의 스칼라 변수를 정의해야한다는 오류가 계속 발생합니다. 여기 내 코드입니다 ... 어떤 도움을 정말로 극명하게 될 것입니다. 죄송 합니다이 코드는 사이트에서 바로 포맷되지 않은 경우이 내 첫 게시물입니다. 미리 감사드립니다.은 SQL INSERT 문에서 scaler 변수를 정의해야합니다.

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(); 
     } 
+1

cmd.Parameters.Add() ... 완전히 누락되었습니다. –

답변

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(); 
    .... 
    } 
    } 
0

은 "준비된 문"을 사용하려면, 당신은 같은 것을 할 필요가 :

당신이 만약 단지 간단한 "삽입"을 원하면 다음과 같이 할 수 있습니다.

string sql = 
    "insert into Region (RegionID, RegionDescription) values ('" + id + 
    "', '" + desc + "')"; 
SqlCommand command = new SqlCommand(sql); 
command.ExecuteNonQuery()