嗨我有测试文件夹,每天我们复制一个csv文件我们不使用任何代码复制文件我们只是从本地拖放。 CSV文件有11列,但我想在sql中只有3列数据。所以我在sql中创建了3列。我的目标是从文件夹中读取文件并将这3列数据插入到sql中。我将每天使用任务调度程序运行任务,如果文件在文件夹中找到它需要将数据导入到sql
答案 0 :(得分:0)
这将为你做到。只需选择要加载的字段(列)即可。
Protected Sub uploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uploadButton.Click
' declare CsvDataReader object which will act as a source for data for SqlBulkCopy
Using csvData = New CsvDataReader(new StreamReader(fileUpload.PostedFile.InputStream, True))
' will read in first record as a header row and
' name columns based on the values in the header row
csvData.Settings.HasHeaders = True
' must define data types to use while parsing data
csvData.Columns.Add("varchar") ' First
csvData.Columns.Add("varchar") ' Last
csvData.Columns.Add("datetime") ' Date
csvData.Columns.Add("money") ' Amount
' declare SqlBulkCopy object which will do the work of bringing in data from
' CsvDataReader object, connecting to SQL Server, and handling all mapping
' of source data to destination table.
Using bulkCopy = New SqlBulkCopy("Data Source=.;Initial Catalog=Test;User ID=sa;Password=")
' set the name of the destination table that data will be inserted into.
' table must already exist.
bulkCopy.DestinationTableName = "Customer"
' mappings required because we're skipping the customer_id column
' and letting SQL Server handle auto incrementing of primary key.
' mappings not required if order of columns is exactly the same
' as destination table definition. here we use source column names that
' are defined in header row in file.
bulkCopy.ColumnMappings.Add("First", "first_name") ' map First to first_name
bulkCopy.ColumnMappings.Add("Last", "last_name") ' map Last to last_name
bulkCopy.ColumnMappings.Add("Date", "first_sale") ' map Date to first_sale
bulkCopy.ColumnMappings.Add("Amount", "sale_amount") ' map Amount to sale_amount
' call WriteToServer which starts import
bulkCopy.WriteToServer(csvData)
End Using ' dispose of SqlBulkCopy object
End Using ' dispose of CsvDataReader object
End Sub ' end uploadButton_Click