2

现在我有一个 SQL Server 表,其中填充了来自外部 .CSV 文件的数据,该文件偶尔会通过附加新数据来更新。最初,我将程序设置为每次运行时都删除表中的所有内容,并且它会从 .CSV 文件上传所有内容。现在我正在尝试重新配置它,以便它只从文件中插入新附加的数据,而不是先删除所有内容。

该程序首先从上传到数组的 .CSV 文件中分隔数据。然后我基本上遍历数组并上传每个元素。现在我有一个包含表中所有当前主键的辅助数组,到目前为止,我已经尝试将这些与正在读取的 .CSV 文件中的主键进行比较。因此,它会检查 .CSV 文件中的主键是否尚未在表/辅助数组中,它会继续进行插入。这似乎是一个合理的逻辑,但由于某种原因我无法让它工作。

这是我的代码的主要内容:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        //Create new SQL connection and adapter using Windows Authentication
        SqlConnection myConnection = new SqlConnection("Data Source=database; Initial Catalog=Dashboard; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
        SqlDataAdapter da = new SqlDataAdapter();

        try
        {
            myConnection.Open();

            da.InsertCommand = new SqlCommand("INSERT INTO DashboardLibAnswer(Id,Date,Time,Question,Details,Answer,Notes,EnteredBy,WhereReceived,QuestionType,AnswerMethod,TransactionDuration)"
                + "VALUES(@Id,@Date,@Time,@Question,@Details,@Answer,@Notes,@EnteredBy,@WhereReceived,@QuestionType,@AnswerMethod,@TransactionDuration)", myConnection);

            da.InsertCommand.Parameters.Add("@Id", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@Date", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Time", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Question", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Details", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Answer", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Notes", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@EnteredBy", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@WhereReceived", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@QuestionType", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@AnswerMethod", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@TransactionDuration", SqlDbType.NVarChar);

            //Using the global variable counter this loop will go through each valid entry and insert it into the specifed database/table
            for (int i = 0; i < counter; i++)
            {
                //This is where I try to do the comparision. 
                //idS is the secondary array with all the current primary keys in the Table
                //collection is the primary array that stores new data from the .CSV file
                if (idS.ElementAt(i) != collection.getIdItems(i))
                {
                    da.InsertCommand.Parameters["@Id"].Value = collection.getIdItems(i);
                    da.InsertCommand.Parameters["@Date"].Value = collection.getDateItems(i);
                    da.InsertCommand.Parameters["@Time"].Value = collection.getTimeItems(i);
                    da.InsertCommand.Parameters["@Question"].Value = collection.getQuestionItems(i);
                    da.InsertCommand.Parameters["@Details"].Value = collection.getDetailsItems(i);
                    da.InsertCommand.Parameters["@Answer"].Value = collection.getAnswerItems(i);
                    da.InsertCommand.Parameters["@Notes"].Value = collection.getNotesItems(i);
                    da.InsertCommand.Parameters["@EnteredBy"].Value = collection.getEnteredByItems(i);
                    da.InsertCommand.Parameters["@WhereReceived"].Value = collection.getWhereItems(i);
                    da.InsertCommand.Parameters["@QuestionType"].Value = collection.getQuestionTypeItems(i);
                    da.InsertCommand.Parameters["@AnswerMethod"].Value = collection.getAnswerMethodItems(i);
                    da.InsertCommand.Parameters["@TransactionDuration"].Value = collection.getTransactionItems(i);
                    da.InsertCommand.ExecuteNonQuery();
                }


                //Updates the progress bar using the i in addition to 1 
                _worker.ReportProgress(i + 1);

            } // end for

            //Once the importing is done it will show the appropriate message
            MessageBox.Show("Finished Importing");

        } // end try
        catch (Exception exceptionError)
        {
            //To show exceptions thrown just uncomment bellow line
            //rtbOutput.AppendText(exceptionError.ToString);

        } // end catch

        //Closes the SQL connection after importing is done
        myConnection.Close();

    } // end backgroundWorker1_DoWork 

现在程序正在执行,但没有插入新数据。似乎该程序没有退出 for 循环,因为如果它成功运行,它会显示“完成导入”消息框。

4

1 回答 1

1

线

if (idS.ElementAt(i) != collection.getIdItems(i))

看起来很奇怪。根据 getIdItems 返回的内容,在我看来,如果两个列表第一次不同步时您将匹配 - 因此,如果项目的出现顺序与您已经持久化它们的顺序不同,您可能会得到一个假阳性。IE。代码将评估该项目不存在并且应该保留,即使它存在于您集合中的其他位置。

然后,如果您有唯一约束,则插入将失败,将您发送到被注释掉的异常处理程序 - 然后退出。

我要做的第一件事是激活异常处理程序以了解发生了什么。其次,我可能会更改上面的代码,以便您查找而不是遍历您的idS集合。IE。如果您制作idS一个列表或包含 Linq 扩展方法,您可以执行以下操作:

if (!idS.Contains(collection.getIdItems(i))

编辑:请注意,对于 large idS,这不是特别有效,并且随着列表的增长也不能很好地扩展。如果您希望处理大量idS,您可能希望将列表更改为哈希集合或使用此处建议的解决方案检查 list<t> 是否包含任何其他列表

于 2013-02-20T15:29:05.877 回答