VB.NET中的Access INSERT INTO语句出错

时间:2013-05-30 17:38:59

标签: vb.net ms-access oledb

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')"

1 个答案:

答案 0 :(得分:0)

您生成的SQL语句的一个潜在问题是'5/29/2013'。 Jet通常使用哈希标记#(不是单引号')作为日期分隔符,因此您可能会通过尝试将字符串分配给日期/时间字段来获得“类型不匹配”错误。

在任何情况下,您都可以使用参数化查询来避免这些问题(以及其他问题,如SQL注入)。它会是这样的:

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()

帮自己一个忙,开始使用这种方法,而不是“粘合”长串的麻烦(和易受攻击的!)SQL代码。