0

I am a beginner at this. But let me explain what I need to do and show you my code

  1. I have a CSV file. inside the CSV I have a projectnumber, city,state,country
  2. I have a SQL table with the same column
  3. I want to use vb.net to check if projectnumber exists in sql table if exists then I want to run update statement. if it does not exists then I want to run insert statement.

I have the program working . but I am just wondering if this would be the correct way or my code is some hack way of doing it.

LEGEND: DTTable is data table with CSV inside

DT is data table with SQL result data

  1. First I fill insert all lines in the CSV into a data table

        Dim parser As New FileIO.TextFieldParser(sRemoteAccessFolder & "text.csv")
        parser.Delimiters = New String() {","}
        parser.ReadLine()
        Do Until parser.EndOfData = True
            DTTable.Rows.Add(parser.ReadFields())
        Loop
        parser.Close()
    
  2. then I use oledbdataadapter to run the select query and fill another data table with the result of the select statement

                SQLString = "select * from tblProjects where ProjectID='" & DTTable.Rows.Item(i).Item("ProjectNumber") & "'"
                da = New OleDb.OleDbDataAdapter(SQLString, Conn)
                da.Fill(dt)
    
  3. then I run if statement

    If dt.Rows.Count = 0 then
        SQLString = "INSERT STATEMENT HERE"
        oCmd = New OleDb.OleDbCommand(SQLString, Conn)
        oCmd.ExecuteNonQuery()
    

    Else SQLString = "UPDATE STATEMENT HERE" oCmd = New OleDb.OleDbCommand(SQLString, Conn) oCmd.ExecuteNonQuery() End if

  4. ALL above code is run inside a for loop, to go through all the lines in the CSV

    For i = 0 To DTTable.Rows.Count - 1

what do you think? please advise

thank you

4

2 回答 2

0

就个人而言,我不会使用 .NET。我会将表导入到临时 SQL Server 表中,然后编写查询以将临时表中的数据插入/更新到常规表中。如果数据集很大,这肯定是您想要的方式。

如果这是您需要经常重复的过程,您可以制作一个 SSIS 包。

于 2013-08-06T18:03:56.553 回答
0

我会使用datareader = command.ExecuteReader(). 然后:

If datareader.Read() then
  'Update query using datareader(0) as a where predicate goes here
ElseIf datareader(0) = Nothing then
  'Insert query goes here
End If

我应该说,我也是一个相对新手,所以也许其他人可以提出一种更优雅的方法。

于 2013-08-07T15:39:33.343 回答