2012-02-09 75 views
1

当我输入数据尚不可用时。按钮不起作用 但是当我输入数据库中的现有数据时,该按钮用于查找数据库中的现有记录以及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 
+1

不要使用这样的字符串连接来构建查询字符串。 EVER! – 2012-02-09 03:17:03

回答

0

我不知道你正在尝试做的时候没有数据库匹配记录,但你没有任何代码,将在没有匹配条目的情况下被击中。

如果没有匹配的记录,则您的while条件不符合,并且循环中没有任何内容发生。

解决它可能涉及重新安排你的循环顺序和你的条件。

检查是否先查看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 

而且正如在乔尔的评论从未被提及,你真的应该看看使用参数化查询。您插入命令的

例如改变:

command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)" 
command.Parameters.AddWithValue("?noK",TextBox1.Text) 
command.Parameters.AddWithValue("?khupd", tkhupd) 
command.ExecuteNonQuery() 
+0

非常感谢。 – ieyla 2012-02-15 03:59:49