【问题标题】:Code Doesn't work. C# Execute Non Query代码不起作用。 C# 执行非查询
【发布时间】:2015-04-03 18:41:50
【问题描述】:
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");
}

在网上找到了代码。请帮助使其工作。谢谢!

【问题讨论】:

  • 请花点时间仔细查看How to Ask
  • 尝试查看ex.Message 并查看内容。它将为您提供有关错误的更多信息。
  • “不起作用”是一个完全无用的问题陈述。请尽可能详细地告诉我们您正在尝试做什么以及它到底是如何不起作用的。
  • 删除可能引发异常的第二个cnn.Open();
  • 警告您的代码极易受到 sql 注入攻击!

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


【解决方案1】:

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

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

【讨论】:

  • 这个“答案”介于答案和评论之间(有更多代表,you will be able to post comments)。请考虑进一步详细说明和格式化以使其成为正确答案,或删除此内容(或让某人将其转换为评论)。
猜你喜欢
  • 2017-03-18
  • 2018-10-19
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多