我从excel导入到sql数据库时更新以前的记录

时间:2015-06-12 13:41:53

标签: c# sql excel import sqlbulkcopy

我需要有关此代码的帮助。我试图从excel导入到SQL数据库。列设置为唯一,以便在发现重复数据时忽略它。在这种情况下,如果有更新,我希望它更新数据而不是忽略它。这是代码;

if (con.State == ConnectionState.Open)
        {
            con.Close();
        }

        con.Open();

        if (comboBox1.SelectedItem.ToString() == "Comissioned Sites")
        {
            string pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFilePath.Text + ";Extended Properties=\"Excel 12.0;HDR=Yes;\";";

            // Create Connection to Excel Workbook
            using (OleDbConnection connection = new OleDbConnection(pathConn))
            {
                OleDbCommand command = new OleDbCommand("Select * FROM [" + txtSheet.Text + "$]", connection);

                connection.Open();

                // Create DbDataReader to Data Worksheet
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    // Bulk Copy to SQL Server
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
                    {
                        con.Open();
                        bulkCopy.DestinationTableName = "tblView";
                        bulkCopy.WriteToServer(dr);
                        con.Close();
                    }
                }
            }
            MessageBox.Show("File Imported to Database Successfully");
        }

1 个答案:

答案 0 :(得分:0)

那么你想要的是什么?看看MERGE

MERGE - MSDN