我有一个导入CSV文件(没有标题行)的应用程序,并将内容写入数据表。然后将数据表作为参数传递给我的DAL中的函数,该函数使用sqlBulkCopy命令将数据写入SQL Server数据库。
我已经将代码测试为Webforms和Windows Forms环境,并注意到在这两种情况下第一行数据都丢失了。有谁知道为什么会这样,我怎么能纠正它?谢谢你的帮助。
我应该补充一点,如果CSV文件有标题行,则不会发生这种情况。
UI
Dim csvFileFolder As String = "D:\PROJECTS\Letters(DOTNET)\TextFiles\"
Dim csvFileName As String = "quad1a.txt"
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)
'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTable
da.Fill(dt)
grdQuad.DataSource = dt
grdQuad.DataBind()
LettersBLL.TemporaryPatientManager.InsertIntoBulkTable(dt)
DAL
Public Shared Function InsertIntoBulkTable(dt As DataTable) As DataTable
Using myConnection As New SqlConnection(ApplicationConfiguration.ConnectionString)
Using sqlBulkCopy As New SqlBulkCopy(myConnection)
'Set the database table name
sqlBulkCopy.DestinationTableName = "tblBulkInsert"
myConnection.Open()
sqlBulkCopy.WriteToServer(dt)
myConnection.Close()
End Using
End Using
Return Nothing
End Function
答案 0 :(得分:0)
试试这个......
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=No;Dbq=" _& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
已添加' HDR =否'到您的连接字符串
或者尝试指定sqlbulkcopy列映射。
MSDN .....
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.columnmappings.aspx
实施例.....
http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy