插入记录时出现错误 [英] Getting error while inserting a record
本文介绍了插入记录时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public int Insert(Student s)
{
con.Open();
cmd = new SqlCommand("Insert into Students (stdid, studname) values" + "(@stdid, @studname)", con);
SqlParameter[] prm = new SqlParameter[2];
prm[0] = new SqlParameter("@stdid",SqlDbType.Int);
prm[1] = new SqlParameter("@studname", SqlDbType.VarChar, 50);
prm[0].Value = s.studentid;
prm[1].Value = s.studentname;
cmd.CommandType = CommandType.Text;
return cmd.ExecuteNonQuery();
}
我遇到这样的错误.
必须声明标量变量"@stdid".
I am getting error like this.
Must declare the scalar variable "@stdid".
推荐答案
您没有将参数添加到命令中,因此将其添加到代码中:
You don''t add the parameters to the command, so add to your code:
...
cmd.Parameters.Add(prm[0]);
cmd.Parameters.Add(prm[1]);
...
您声明了一个新的参数块,但是您不使用它!
试试:
You declare a new parameters block, but you don''t use it!
Try:
public int Insert(Student s)
{
con.Open();
cmd = new SqlCommand("Insert into Students (stdid, studname) values" + "(@stdid, @studname)", con);
// SqlParameter[] prm = new SqlParameter[2];
// prm[0] = new SqlParameter("@stdid",SqlDbType.Int);
// prm[1] = new SqlParameter("@studname", SqlDbType.VarChar, 50);
// prm[0].Value = s.studentid;
// prm[1].Value = s.studentname;
cmd.Parameters.AddWithValue("@stdid", s.studentid);
cmd.Parameters.AddWithValue("@studname", s.studentname);
cmd.CommandType = CommandType.Text;
return cmd.ExecuteNonQuery();
}
请注意,如上所示,Parameters.Add(您正在有效使用的)已折旧,而改为使用AddWithValue.
Note that Parameters.Add (which you are effectively using) is depreciated in favour of AddWithValue, as shown above.
请尝试以下操作:
创建SqlParameter最佳做法
C#SqlParameter示例
C#SQL插入
Try following:
Creating SqlParameters Best Practices
C# SqlParameter Example
C# SQL INSERT
这篇关于插入记录时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文