[英]Cannot insert explicit value for identity column in table 'candidatedetails' when IDENTITY_INSERT is set to OFF
I am geting this error. 我正在解决这个错误。 How should I solve this?
我该怎么解决这个问题?
This is my create query 这是我的创建查询
CREATE TABLE [dbo].[candidatedetails](
[id] [int] IDENTITY(1,1) NOT NULL,
[cname] [varchar](50) NULL,
[pname] [varchar](50) NULL,
[cno] [varchar](50) NULL,
[pno] [varchar](50) NULL,
[address] [varchar](max) NULL,
[year] [varchar](50) NULL,
[class] [varchar](50) NULL,
[branch] [varchar](50) NULL,
[totalfees] [numeric](18, 0) NULL,
[paidfees] [numeric](18, 0) NULL,
[pendingfees] [numeric](18, 0) NULL,
[idno] [int] NULL,
CONSTRAINT [PK_candidatedetails] PRIMARY KEY CLUSTERED
(
[id] ASC
)
This is the code 这是代码
SqlConnection con = new SqlConnection(constring);
con.Open();
if(con.State==ConnectionState.Open)
{
string q = "INSERT INTO candidatedetails(id,cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('','"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
SqlCommand com = new SqlCommand(q, con);
com.ExecuteNonQuery();
MessageBox.Show("Candidate is registered");
}
I am getting this error on line "com.executenonquery()" 我在“com.executenonquery()”行上收到此错误
Your id
column is declared as IDENTITY
so it auto-generates a value on insertion. 您的
id
列被声明为IDENTITY
因此它会在插入时自动生成一个值。 You don't have to include it on your insert column list nor supply a value for it. 您不必将其包含在插入列列表中,也不必为其提供值。
string q = "INSERT INTO candidatedetails(cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
Also, beware of generating your SQL dynamically like this, it's prone to errors (if one of your values has an unescaped single quote for example) and to SQL injection if the values come from user input or another unsafe source. 另外,要注意像这样动态生成SQL,它容易出错 (例如,如果你的一个值有一个未转义的单引号),如果值来自用户输入或另一个不安全的源,则会出现SQL注入 。
You should either create a Stored Procedure that receives these parameters, or build the sql with sp_executesql
. 您应该创建一个接收这些参数的存储过程,或者使用
sp_executesql
构建sql。
just Remove id form sql query: Try this: 只需删除id表单sql查询:试试这个:
SqlConnection con = new SqlConnection(constring);
con.Open();
if(con.State==ConnectionState.Open)
{
string q = "INSERT INTO candidatedetails(cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
SqlCommand com = new SqlCommand(q, con);
com.ExecuteNonQuery();
MessageBox.Show("Candidate is registered");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.