JayBeeOH

SQL Bulk Copy Demo (Console App.)

Jun 3rd, 2015
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 4.93 KB | None | 0 0
  1. '------------------------------------------------------------------------------------------
  2. '           Notice of My Copyright and Intellectual Property Rights
  3. '
  4. ' Any intellectual property contained within the program by Joseph L. Bolen remains the
  5. ' intellectual property of the Joseph L. Bolen. This means that no person may distribute,
  6. ' publish or provide such intellectual property to any other person or entity for any
  7. ' reason, commercial or otherwise, without the express written permission of Joseph L. Bolen.
  8. '
  9. '                 Copyright © 2015. All rights reserved.
  10. '        All trademarks remain the property of their respective owners.
  11. '-------------------------------------------------------------------------------------------
  12. ' Program Name:   SQL Bulk Copy Demo (Console App.)
  13. '
  14. ' Author:         Joseph L. Bolen
  15. ' Date Created:   June 2015
  16. '
  17. ' Description:    Quick insert of records from a Comma Separated Variable (CSV) file into
  18. '                 a "previously defined table" in a SQL type server. Demo is using the input file
  19. '                 called "MyTable.csv" in the MyDocument folder. The output is to a database
  20. '                 table name "Contacts".
  21. '
  22. '                 NOTE: To use, change the hardcoding of the scrFile and targetTable variables.
  23. '                 Also, if the csv file has or has not a Header columns row, then change the
  24. '                 HasColumnHeadings variable. In addition, modify in the App.config file for
  25. '                 the correct ConnectionString.
  26. '
  27. '                 Documentation is at:
  28. '                   App's Visual Basic .NET code is at http://pastebin.com/u/jaybeeoh
  29. '                   Video tutorial at YouTube: http://www.youtube.com/user/bolenpresents
  30. '-------------------------------------------------------------------------------------------
  31.  
  32. Imports System.Data
  33. Imports System.Data.SqlClient
  34. Imports System.IO
  35. Imports System.Configuration
  36.  
  37. '   1) You must add System.Configuration as a reference to the project.
  38. '   2) You must modify the App.Config file to have a
  39. '      named connection string:
  40.  
  41. '               <connectionStrings>
  42. '               <clear />
  43. '               <add name="AppConnStr"
  44. '                   providerName="System.Data.SQLClient"
  45. '                   connectionString="Server=.\SQLEXPRESS; Database=SimpleDB; Integrated Security=True;" />
  46. '               </connectionStrings>
  47.  
  48. Module BulkCopyLoad
  49.  
  50.     Sub Main()
  51.  
  52.         Dim inputSrc As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\MyTable.csv"
  53.         Dim targetTable As String = "Contacts"
  54.         Dim HasColumnHeadings As Boolean = True
  55.  
  56.         Dim dt As New DataTable
  57.         Dim line As String = Nothing
  58.  
  59.         Using sr As StreamReader = File.OpenText(inputSrc)
  60.             ' Prime the pump read.
  61.             line = sr.ReadLine()
  62.  
  63.             Do While line IsNot Nothing
  64.                 Dim data() As String = line.Split(","c)
  65.                 If data.Length > 0 Then
  66.  
  67.                     If HasColumnHeadings Then
  68.                         For Each item In data
  69.                             dt.Columns.Add(New DataColumn(item.ToString))
  70.                         Next item
  71.                         HasColumnHeadings = False
  72.                     Else
  73.                         Dim row As DataRow = dt.NewRow()
  74.                         row.ItemArray = data
  75.                         dt.Rows.Add(row)
  76.                     End If
  77.                 End If
  78.                 line = sr.ReadLine()
  79.             Loop
  80.         End Using
  81.  
  82.         Dim connStr As String = ConfigurationManager.ConnectionStrings("AppConnStr").ConnectionString
  83.         Using con As New SqlConnection(connStr)
  84.             con.Open()
  85.             'Using copy As New SqlBulkCopy(connStr)
  86.             Using copy As New SqlBulkCopy(connStr, SqlBulkCopyOptions.TableLock) ' Performance improvement.
  87.                 Try
  88.                     'copy.ColumnMappings.Add([inputSrc's Header or Ordinal Position], [TargetTable's Column Header or Ordinal Position])
  89.                     'copy.ColumnMappings.Add("ContactId", "ContactId")
  90.                     'copy.ColumnMappings.Add(0, 0)
  91.                     'copy.ColumnMappings.Add(1, 1)
  92.                     'copy.ColumnMappings.Add(2, 2)
  93.                     'copy.ColumnMappings.Add(3, 3)
  94.                     copy.DestinationTableName = targetTable
  95.                     copy.WriteToServer(dt)
  96.                     Console.WriteLine()
  97.                     Console.WriteLine("SqlBulkCopy completed. " & dt.Rows.Count.ToString & " records were processed.")
  98.                 Catch ex As Exception
  99.                     Console.WriteLine()
  100.                     Console.WriteLine("Error occured durring processing.")
  101.                     Console.WriteLine("Message: " & ex.Message)
  102.                 End Try
  103.             End Using
  104.         End Using
  105.  
  106.         Console.WriteLine()
  107.         Console.WriteLine("Press any key to exit.")
  108.         Console.ReadKey()
  109.     End Sub
  110.  
  111. End Module
Advertisement
Add Comment
Please, Sign In to add comment