我正在尝试编写包含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();
}
答案 0 :(得分: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();
....
}
}
答案 1 :(得分:0)
如果你想使用“预备陈述”(总是可取的),你需要做这样的事情:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare%28v=vs.71%29.aspx
rConn.Open()
Dim command As SqlCommand = New SqlCommand("", rConn)
' Create and prepare an SQL statement.
command.CommandText = "insert into Region (RegionID, RegionDescription) values (@id, @desc)"
command.Parameters.Add("@id", id)
command.Parameters.Add("@desc", desc)
command.Prepare() ' Calling Prepare after having set the Commandtext and parameters.
command.ExecuteNonQuery()
如果您只想要一个简单的“插入”,那么您可以这样做:
string sql =
"insert into Region (RegionID, RegionDescription) values ('" + id +
"', '" + desc + "')";
SqlCommand command = new SqlCommand(sql);
command.ExecuteNonQuery()