我发现了这个错误。我该怎么解决这个问题?
这是我的创建查询
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
)
这是代码
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");
}
我在“com.executenonquery()”
行上收到此错误答案 0 :(得分:2)
您的id
列被声明为IDENTITY
,因此它会在插入时自动生成一个值。您不必将其包含在插入列列表中,也不必为其提供值。
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+"')";
另外,要注意像这样动态生成SQL,容易出错(例如,如果你的某个值有未转义的单引号)和 SQL注入如果值来自用户输入或其他不安全的来源。
您应该创建一个接收这些参数的存储过程,或者使用sp_executesql
构建sql。
答案 1 :(得分:1)
只需删除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");
}