I want to insert records in the database but before it inserts, it must first check the database whether the value being inserted already exists. Now my problem is that I am unable to insert into the database even though the value still does not exist.
Here’s my code:
Dim check As New SqlCommand
Dim sqlcheck As String = "SELECT SerialNumber FROM EquipmentDetail WHERE SerialNumber = '" & TextBox1.Text & "'"
connection.Open()
check.Connection = connection
check.CommandText = sqlcheck
Dim read As SqlDataReader = check.ExecuteReader()
If read.HasRows Then
While read.Read()
If read("SerialNumber").ToString() = TextBox1.Text Then
MessageBox.Show(read("SerialNumber").ToString() & " was already added")
Else
cmd.Connection = connection
cmd.CommandText = "INSERT INTO EquipmentDetail (SerialNumber, BoxNumber, FATTNumber, FaultTicketNumber, Description, ProductCode)" &
"VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', '" & TextBox4.Text & "', '" & TextBox6.Text & "', '" & ComboBox1.Text & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("Equipment successfully added.", "Equipment", MessageBoxButtons.OK)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox6.Text = ""
TextBox1.Focus()
connection.Close()
End If
End While
End If
read.Close()
There are a number of issues with your code.
First, you have an sql injection vulnerability which can be resolved using parameters.
Second, you are performing database activities within an open datareader, which could lead to numerous issues.
Third, you are performing far too much work to determine whether or not the serial number exists. You can make use of the SQL Server Exists statement and the SqlCommand’s ExecuteScalar method to return and test a single value, which makes the code much faster and easier to understand.
Finally, you need to ensure that disposable items are disposed and the easiest/best way to do this is through the use of Using blocks.
These can all be resolved with the following code: