我试图从txt文件读取并写入数据库并获取pk错误

时间:2014-12-07 20:19:59

标签: sql-server vb.net

我有读写器部分工作,但如果txt文件中的数据已经存在于数据库中,我会一直收到pk错误。如何检查两个文件中的pk?

Imports System.IO
Imports System.Data.SqlClient

Public Class Form1

Public AllEmp As New List(Of NEEmployee)

Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
    getEmployeesFromFile()
    dgvEmployees.DataSource = AllEmp
End Sub

Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click


    For Each emp As NEEmployee In AllEmp
        InsertAnEmployee(emp)
    Next

End Sub

Private Sub getEmployeesFromFile()
    Dim reader As StreamReader
    Try
        reader = File.OpenText("employee.txt")
        While reader.EndOfStream = False
            Dim strEmp As String() = reader.ReadLine().Split(CChar("|"))
            Dim emp As New NEEmployee
            emp.EmpID = CInt(strEmp(0))
            emp.FirstName = strEmp(1)
            emp.LastName = strEmp(2)
            emp.Department = strEmp(3)
            emp.Shift = CInt(strEmp(4))
            emp.PayClass = strEmp(5)
            emp.CompanyLocation = strEmp(6)
            AllEmp.Add(emp)
        End While
        reader.Close()
    Catch ex As Exception
        Throw ex
    End Try
End Sub

Public Function InsertAnEmployee(ByVal Emp As NEEmployee) As Integer

    Dim Command As SqlCommand
    Dim Connection As SqlConnection
*emphasized text*
        Try

            ' instantiate a SQL connection and command
            Connection = New SqlConnection("Data Source=SAMJULIE-PC\SAMJULIE;Initial Catalog=NESgillis;Integrated Security=True;Pooling=False")
            Command = New SqlCommand

            ' define the type of command
            Command.CommandText = String.Format("INSERT INTO NEEmployee (EmpID, FName, LName, Department, Active, Shift, WageClass, CompanyLocation) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')", _
                                                Emp.EmpID, Emp.FirstName, Emp.LastName, Emp.Department, Emp.Department, Emp.Shift, Emp.PayClass, Emp.CompanyLocation)
            Command.CommandType = CommandType.Text
            Command.Connection = Connection

            ' open connection and read data
            Connection.Open()

            InsertAnEmployee = Command.ExecuteNonQuery()

            ' close and clean up objects
            Connection.Close()
            Connection.Dispose()
            Command.Dispose()

        Catch ex As Exception
            Throw ex
        End Try
    End If
    Return InsertAnEmployee

End Function

End Class

Public Class NEEmployee
    Property EmpID As Integer
    Property FirstName As String
    Property LastName As String
    Property Department As String
    Property Shift As Integer
    Property PayClass As String
    Property CompanyLocation As String
End Class

1 个答案:

答案 0 :(得分:1)

如果您根本不担心并发(即,一次只运行一个客户端运行此导入),您只需将Insert查询修改为:

Command.CommandText = String.Format("IF NOT EXISTS (SELECT * FROM NEEmployee WHERE EmpID={0}) INSERT INTO NEEmployee (EmpID, FName, LName, Department, Active, Shift, WageClass, CompanyLocation) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')", _
                                            Emp.EmpID, Emp.FirstName, Emp.LastName, Emp.Department, Emp.Department, Emp.Shift, Emp.PayClass, Emp.CompanyLocation)

但是,如果有多个客户端可能并行导入,那么您仍会偶尔看到PK违规。如果是这样的话,请参阅此主题以获取您的选项: Only inserting a row if it's not already there

另一个观察结果(尽管与您的问题没有直接关系):您的SQL容易受到SQL注入攻击,因为您使用的是简单的字符串替换。有关在VB.NET中使用SqlCommand Parameters对象的简单示例,请参阅此主题:How to use parameters "@" in an SQL command in VB