2012-02-09 4 views
1

데이터를 아직 사용할 수 없습니다. 버튼이 작동하지 않습니다 하지만 데이터베이스에 기존 데이터를 입력하면 버튼이 데이터베이스 및 msgbox.appear 기존 레코드를 찾기 위해 작동합니다.이 코드는 입니다.새 데이터를 삽입 할 때 버튼이 작동하지 않습니다. 데이터를 입력 할 때

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

쿼리 문자열을 구축하는 그런 문자열 연결을 사용하지 마십시오. 이제까지! –

답변

0

난 당신이 데이터베이스에서 일치하는 기록이 없을 때 뭘 하려는지 확실하지 않다 (나는 마이크로 소프트 비주얼 베이직 2008 익스프레스 에디션 데이터베이스 MySQL을 사용하고있다),하지만 당신은 것 코드가없는 일치하는 항목이없는 경우 적중됩니다.

일치하는 레코드가 없으면 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 

그리고 조엘의 코멘트에 언급 된 바와 같이, 당신이 정말로 매개 변수화 된 쿼리를 사용하여보고해야한다. 변경하여 삽입 명령의

예 :

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

관련 문제