检查更新命令,我的语法错误吗?

时间:2013-09-27 06:11:18

标签: sql vb.net

他的全部, 我正在研究cms,在尝试更新命令更新记录时,它无效。

这是完整的更新代码,

Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone, CheckupDate, Disease, BloodGroup, Doctor, Remarks As String

    RegNo = txtRegNo.Text
    BedNo = CmbBedNo.SelectedItem.ToString()
    BedType = CmbBedType.SelectedItem.ToString()
    Charges = txtCharges.Text
    PatName = txtPatName.Text
    PatAge = txtPatAge.Text
    PatAddr = txtPatAdd.Text
    Phone = txtPhone.Text
    CheckupDate = txtDate.Text
    Disease = txtDisease.Text
    BloodGroup = cmbBloodGrp.SelectedItem.ToString()
    Doctor = cmbDoctor.SelectedItem.ToString()
    Remarks = txtRemarks.Text

    ID = txtRegNo.Text

    Dim conStudent As New OleDbConnection
    Dim comStudent As New OleDbCommand


    conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
    conStudent.Open()

    comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ", Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" & Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ", Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" & CheckupDate & "', Disease='" & Disease & "', BloodGroup='" & BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "' WHERE ID=" & RegNo

    comStudent.Connection = conStudent

    comStudent.CommandType = CommandType.Text

    If (comStudent.ExecuteNonQuery() > 0) Then
        MsgBox("record successfully updated")
    End If

    conStudent.Close()

一件事,用ID,BedNo,BedCharges,Age命名的字段设置为Number作为数据类型。

1 个答案:

答案 0 :(得分:0)

首先,切换到参数化查询。这将删除Sql Injection的任何可能性,但也避免引用字符串,解析十进制数和日期的问题

Dim conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
Dim cmdText =   "UPDATE AdmitPt SET ID =?, Bedcategory=?, BedNo=?, BedCharges=?, " & _
                "PtName=?, PtAge=?, Address=?, PhoneNo=?, Dates=?, Disease=?, " & _
                "BloodGroup=?, Doctor=?, Remarks=? WHERE ID=?"
Using conStudent = new OleDbConnection(conString)
Using comStudent = new OleDbCommand(cmdText, conStudent)
     conStudent.Open()
     comStudent.Parameters.AddWithValue("@p1", Convert.ToInt32(ID))
     comStudent.Parameters.AddWithValue("@p2", BedType)
     comStudent.Parameters.AddWithValue("@p3", Convert.ToInt32(BedNo))
     comStudent.Parameters.AddWithValue("@p4", Convert.ToDecimal(Charges))
     .... and so on for every other question marks in the cmdText ....
     .... respecting the exact order of the fields ...................
     .... try also to pass the correct datatype for every non string field
    If (comStudent.ExecuteNonQuery() > 0) Then
        MsgBox("record successfully updated")
    End If
End Using
End Using