更新时间:2023-02-14 21:27:43
列RegNo,Name,Address,CreatedTime。在我的代码中遇到以下错误。
必须声明标量变量@RegNo 。
该怎么做。
当您创建参数化查询时 - 这正是执行SQL操作的正确方法 - 您还必须创建一个包含您希望传递给SQL的值的参数。这有点像在C#中调用方法。你定义它public int DoInsert ( int regNo, string name, string 地址,日期时间insertDate)
{
...
}但是当你调用它时,你必须提供值:
int rowsAffected = DoInsert( 666 , Mike Smith, 2 Main Street,Kentucky,DateTime.Now);如果你遗漏了任何参数,就会出现编译错误。
SQL是一样的。
为每个参数添加一行:cmd.Parameters.AddWithValue( @ NameOfParameterInSQLCommand,valueIWantInTheColumn );
它将开始起作用。
protected void Add_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
//SqlCommand cmd = new SqlCommand("insert into Student values('" + RegNo.Text + "','" + Name.Text + "','" + Address.Text + "')");
SqlCommand cmd = new SqlCommand("insert into Student(@RegNo,@Name,@Address,@CreatedTime) values(@RegNo,@Name,@Address,Getdate())");
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
What I have tried:
here am try to insert records . i have 3 textboxes namely RegNo,Name,Address and in my table I have $ columns RegNo,Name,Address,CreatedTime. in my code the following error encountered .
Must declare the scalar variable @RegNo .
what to do.
columns RegNo,Name,Address,CreatedTime. in my code the following error encountered .
Must declare the scalar variable @RegNo .
what to do.
When you create a parameterised query - and that is exactly the right way to do SQL operations - you have to also create a Parameter which contains teh value you wish to pass to SQL. It's a bit like calling a method in C#. You define itpublic int DoInsert(int regNo, string name, string address, DateTime insertDate) { ... }But when you call it, you must provide the values:
int rowsAffected = DoInsert(666, "Mike Smith", "2 Main Street, Kentucky", DateTime.Now);If you miss out any parameters, you get a compiler error.
SQL is the same.
Add a line for each parameter:cmd.Parameters.AddWithValue("@NameOfParameterInSQLCommand", valueIWantInTheColumn);And it'll start to work.