代码不起作用。 C#执行非查询

时间:2015-04-03 18:41:50

标签: c# sql-server-2008 ado.net executenonquery

string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;

conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial  Catalog=DBMSI;Integrated Security=True";

sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";

cnn = new SqlConnection(conStr);

try
{
    cnn.Open();
    cnn = new SqlConnection(conStr);
    cmd = new SqlCommand(sql, cnn);

    cmd.ExecuteNonQuery();

    cmd.Dispose();

    cnn.Open();

    MessageBox.Show("Employee Details registered Succesffuly");
    // Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program. 
}
catch (Exception ex)
{
    MessageBox.Show("Error Occoured - Employee Details were not recorded");
}

在线找到代码。请帮助它的工作。谢谢!

1 个答案:

答案 0 :(得分:0)

希望您在CEC_Employee上的主键不是" empid"并且如果它被设置为自动编号,如IDENTITY(1,1),则SQL命令将失败,因为它赢了&# 39; t让你把它交给主键值。

这当然是猜测,因为您还没有发布实际的异常消息或堆栈跟踪。