当我输入数据时尚未提供。按钮不起作用 但是当我在数据库中输入现有数据时,该按钮用于查找数据库和msgbox.appear中的现有记录 这是我的编码。 (我使用的是Microsoft Visual Basic 2008快速版数据库mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
答案 0 :(得分:0)
我不确定当数据库中没有匹配的记录时你想要做什么,但是没有任何代码会在没有匹配条目的情况下被击中。
如果没有匹配的记录,则不满足您的while条件,并且循环中不会发生任何事情。
修复它可能涉及重新排列循环的顺序和if条件。
检查data.hasRows是否优先。
示例:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
正如Joel的评论中所提到的,你真的应该看看使用参数化查询。
更改了插入命令的示例:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()