我有一个代码来确定数据是否已经存在。问题是,它甚至还在添加,甚至已经存在。
已经尝试了一些将添加或不添加数据的代码
If txtHostname.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Dim theQuery As String = "SELECT * FROM Asset WHERE Monitor1=@Monitor1 AND Monitor2=@Monitor2"
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, con)
cmd1.Parameters.AddWithValue("@Monitor1", txtMonitor1.Text)
cmd1.Parameters.AddWithValue("@Monitor2", txtMonitor2.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Asset ([Monitor1],[Monitor2]) values ('" + txtMonitor1.Text + "','" + txtMonitor2.Text + "')", con2)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = ""
txtMonitor2.Text = ""
End If
End Using
con.Close()
End If
应该是,当我在列1中搜索1个数据时,它应该检测列1和列2中是否已经存在数据。不只是在column1中。
答案 0 :(得分:0)
好吧,如果您想搜索并返回有关字段是否存在的结果,则不应使用 OledbReader ,我也确实注意到reader
不是Read
(即使在这种情况下使用它也不正确)。您宁愿使用ExecuteScalar
来查看字段是否存在(> 0或<0 )。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CMDText As String = ("SELECT COUNT(*) FROM Asset WHERE Monitor1=@Monitor1 AND Monitor2=@Monitor2")
Dim Found As Integer
If String.IsNullOrEmpty(txtHostname.Text) Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Using CN As New OleDb.OleDbConnection With {.ConnectionString = "CON_STR"},
Cmd1 As New OleDb.OleDbCommand(CMDText, CN)
CN.Open()
With Cmd1.Parameters
.Add("@Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("@Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Found = Cmd1.ExecuteScalar()
End Using
If Found > 0 Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim CmdText1 As String =
("INSERT INTO Asset (Monitor1,Monitor2) VALUES (@Monitor1 ,@Monitor2)")
Using Cmd As New OleDb.OleDbCommand(CmdText1, CN)
With Cmd.Parameters
.Add("@Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("@Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Cmd.ExecuteNonQuery()
' User does not exist, add them
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = String.Empty
txtMonitor2.Text = String.Empty
Cmd.Parameters.Clear()
End Using
End If
End If
End Sub
在我的示例代码中:“ CON_STR” =我用来测试代码的ConnectionString,因为您未提供任何代码。