2013-11-23 106 views
0
Imports System.Data.OleDb 
Public Class Form1 
    Dim con As New OleDbConnection 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\sjmi.alfie\documents\visual studio 2010\Projects\Sample Ko\WindowsApplication4\MySample.accdb" 
     If con.State = ConnectionState.Closed Then 
      con.Open() 
      MsgBox("connection is open", vbInformation) 
     Else 
      MsgBox("connection is close", vbCritical) 
     End If 
    End Sub 
    Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeButton.Click 
     Me.Close() 
    End Sub 

    Private Sub regButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles regButton.Click 

     Dim strsql As String 
     Dim numrows As Integer 
     strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = " & TextBox1.Text & "" 
     Dim objcmd As New OleDbCommand(strsql, con) 
     numrows = objcmd.ExecuteScalar() <<<< Error "Data type mismatch in criteria." 

     If numrows > 0 Then 
      MsgBox("Record Exists", vbInformation, "Add") 
     Else 
      Dim myadapter1 As New OleDbDataAdapter("INSERT INTO [Sample] ([StudNo], [FirsName], [LastName]) VALUES ('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "')", con) 
      Dim mytable1 As New DataTable 
      myadapter1.Fill(mytable1) 
      MsgBox("Success!!") 
     End If 
     con.Close() 
    End Sub 
End Class 

請幫幫我。由於檢查數據是否存在於數據庫VB.Net

+0

請正確標記您的代碼並清楚解釋問題。 – varocarbas

+0

請正確縮進您的代碼 – Siva

+0

@varocarbas:作爲我的評論代碼的一部分,我評論了上述政治家,我的意思是包括你的stmt也,我剛纔請求OP。雖然我不是VB.NET的專家,但我想幫助象你這樣的專家,不浪費時間閱讀雜亂的代碼 – Siva

回答

0

試試這個:

strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = ?" 
Dim objcmd As New OleDbCommand(strsql, con) 
objcmd.Parameters.AddWithValue("?", TextBox1.Text) 
numrows = Convert.ToInt32(objcmd.ExecuteScalar()) 

它被稱爲「參數化查詢」,它是做你想要什麼樣的首選方式。

相關問題