0
我有讀寫器部分正常工作,但如果txt文件中的內容已存在於數據庫中,我會一直收到pk錯誤。我如何在兩個文件中檢查PK?我正在嘗試從txt文件讀取數據並寫入數據庫並獲取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