我正在使用MS Access数据库。现在我必须更新特定的单元格值。这是我的代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
此代码更新该列中的所有单元格。我想只更新具有Case_ID = str的特定单元格 我必须添加WHERE子句(WHERE Case_ID =“& str&”
答案 0 :(得分:1)
我会使用命令参数,neater并防止SQL注入问题。类似的东西:
cmd.CommandText = "UPDATE Casehistory set Prescription =@Presc WHERE Case_ID = @CaseID"
cmd.Parameters.AddWithValue("@Presc", Presc.ToString())
cmd.Parameters.AddWithValue("@CaseID",str)
顺便说一句,在按钮点击事件中包含所有这些代码并不理想。您可能希望以更易于维护的方式调查构建应用程序 - 例如,可能使用Data Layer。
答案 1 :(得分:0)
Where子句应附加到OleDbCommmand.CommandText的末尾,您可以在其中定义Update语句。