2015-04-03 33 views
-4
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"); 
} 

在线找到该代码。请帮助使其工作。谢谢!代码不起作用。 C#执行非查询

+4

请花点时间仔细阅读此* *:[Ask] – Plutonix 2015-04-03 18:43:27

+0

尝试查看'ex.Message'并查看内容。它会给你更多关于错误的信息。 – 2015-04-03 18:43:58

+0

什么是异常消息和堆栈跟踪?你自己做了什么才能使它工作?它期望一个带有表格的数据库,根据连接字符串中的任何内容进行配置 - 您是否具有本地的所有设置? – 2015-04-03 18:44:02

回答

0

希望您的CEC_Employee上的主键不是“empid”,并且如果它设置为自动编号,如IDENTITY(1,1),则SQL命令将失败,因为它不会让您将其交给主键值。

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

+1

这个“答案”介于答案和评论之间(多一点的代表,你可以发表评论)(http://stackoverflow.com/privileges/comment))。请考虑详细阐述和格式化以使其成为正确的答案,或删除此内容(或让某人将其转换为评论)。 – ryanyuyu 2015-04-03 19:45:33