0
Private Sub submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit.Click
    Dim con As New OleDb.OleDbConnection
    Dim cmd As New OleDb.OleDbCommand
    Dim dbProvider As String = "PROVIDER = Microsoft.Jet.OleDb.4.0;"
    Dim dbSource As String = "DATA SOURCE =" & Application.StartupPath & "\hospital.mdb"
    con.ConnectionString = dbProvider & dbSource
    If Not con.State = ConnectionState.Open Then
        con.Open()
    End If
    cmd.Connection = con
    cmd.CommandText = "INSERT INTO userdata(masterid, pname, aname, dob, bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone)" & _
    "VALUES ('" & Me.masterid.Text & "','" & Me.pname.Text & "','" & Me.aname.Text & "','" & Me.dob.Text & "','" & Me.bloodgroup.Text & "','" & _
    Me.address.Text & "','" & Me.gender.Text & "','" & Me.referto.Text & "','" & Me.designation.Text & "','" & Me.relh.Text & "','" & Me.mpass.Text & "','" & _
    Me.ward.Text & "','" & Me.bed.Text & "','" & Me.zone.Text & "')"
    cmd.ExecuteNonQuery()

    con.Close()
End Sub

cmd.Commandtext 中的值是

"INSERT INTO userdata(masterid, pname, aname, [dob], bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone)VALUES ('305201323114','fsdfsd','sdfsd','5/29/2013','AB+','sdfsd','Male','sdfsd','sdfsd','sdfsd','sdfdsf','sdfsdf','dfds','North East Zone')"
4

1 回答 1

0

One potential problem with the SQL statement you generated is '5/29/2013'. Jet normally uses hash marks # (not single quotes ') as date delimiters so you may be getting a "Type mismatch" error by trying to assign a string to a Date/Time field.

In any case, you can avoid these kinds of problems (and others, like SQL Injection) by using a parameterized query. It would go something like this:

cmd.CommandText = "INSERT INTO userdata (masterid, pname, aname, dob, bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone) " & _
    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
cmd.Parameters.AddWithValue("?", Me.masterid.Text)
cmd.Parameters.AddWithValue("?", Me.pname.Text)
cmd.Parameters.AddWithValue("?", Me.aname.Text)
' [... and so on ...]
cmd.Parameters.AddWithValue("?", Me.zone.Text)
cmd.ExecuteNonQuery()

Do yourself a favour and start using this method instead of "gluing together" long strings of troublesome (and vulnerable!) SQL code.

于 2013-05-30T21:15:15.027 回答