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
请帮帮我。感谢
答案 0 :(得分: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())
它被称为“参数化查询”,它是做你想做的事情的首选方式。