0

我在 c# 中有一个接受列表的方法,它的目的是将它插入到 SQL Server 表中,但它根本不插入,你能帮我吗?非常感谢任何见解。

这是我的代码

public void insertToDB(List<PlantillaData> plantillaDataList)
{
   IsqlConnect db = new IsqlConnect();
   string conQuery = db.connectionQuery;
   SqlConnection con = new SqlConnection(conQuery);

   try
   {
      con.Open();

      foreach (PlantillaData plantillaData in plantillaDataList)
      {
         SqlCommand cmd = new SqlCommand("INSERT INTO dbo.t_employee(Telephone_Number_1," +
                    "Employee_Number,Employee_LastName,Employee_FirstName,Employee_MiddleName," +
                    "Cluster,Division,Department,Unit,Supervisor,Email,EWB_Rank,Position," +
                    "Location,Employee_Category)VALUES(@telNum1,@empNum,@empLastName,@empFirstName," +
                    "@empMiddleName,@cluster,@division,@unit,@supervisor,@email,@rank," +
                    "@position,@location,@emp_cat) ", con);

         cmd.Parameters.Add("@telNum1", SqlDbType.VarChar).Value = plantillaData.telOneVal;
         cmd.Parameters.Add("@empNum", SqlDbType.Int).Value = plantillaData.empNumVal;
         cmd.Parameters.Add("@empLastName", SqlDbType.VarChar).Value = plantillaData.lName;
         cmd.Parameters.Add("@empFirstName", SqlDbType.VarChar).Value = plantillaData.fName;
         cmd.Parameters.Add("@empMiddleName", SqlDbType.VarChar).Value = plantillaData.mName;
         cmd.Parameters.Add("@cluster", SqlDbType.VarChar).Value = plantillaData.clusterVal;
         cmd.Parameters.Add("@division", SqlDbType.VarChar).Value = plantillaData.divVal;
         cmd.Parameters.Add("@unit", SqlDbType.VarChar).Value = plantillaData.unitVal;
         cmd.Parameters.Add("@supervisor", SqlDbType.VarChar).Value = plantillaData.supervisorVal;
         cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = plantillaData.emailVal;
         cmd.Parameters.Add("@rank", SqlDbType.VarChar).Value = plantillaData.rankVal;
         cmd.Parameters.Add("@position", SqlDbType.VarChar).Value = plantillaData.posVal;
         cmd.Parameters.Add("@location", SqlDbType.VarChar).Value = plantillaData.locVal;
         cmd.Parameters.Add("@emp_cat", SqlDbType.VarChar).Value = 1;

         try
         {
             con.Open();
             cmd.ExecuteNonQuery();
         }
         catch
         {
         }
         finally
         {
             con.Close();
         }
      }
   }
   catch (Exception e)
   {
      throw new Exception("SQL Error:" + e.Message.ToString());
   }
   finally
   {
      con.Close();
   }
}
4

2 回答 2

1

您在单元之前的插入查询中缺少 VALUES 字段的部门值。如果您已捕获并显示错误,您将获得违规

于 2013-08-02T10:07:12.893 回答
0

为什么要打开连接两次?您确定您的列表中有项目吗?你有任何例外吗?

内部 catch 将阻止调用外部 catch 块!

于 2013-08-02T10:05:35.170 回答