我是VB.net编码的新手,并设计了一个代码,它将通过Do While OleDbDataReader.Read
循环读取表中每一行的一列表,并更新列mont
零。
代码运行时没有任何错误,但是当我打开表查看更改时,它们不在那里,即如果我们通过值传递
tempMontComputer (Integer)
但是,如果我直接将值放在SQL查询中,而不是使用
SET mont = @mont
使用
SET mont = 55
存储该值并更新表。
表由列
组成emp_id
(文字)emp_name
(文字)emp_comp_amt
(号码)installment
(号码)mont
(号码)这是我的代码:
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public databasepath As String = Application.StartupPath & "\EMPLOYEES.accdb"
Public connString As String = provider & databasepath
Public myConnection As OleDbConnection = New OleDbConnection
Public cmdUpdateAdvCompu As New OleDbCommand
Public DRAdvComputer As OleDbDataReader
Public tempMontComputer As Integer
Private Sub frmCalculateData_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myConnection.ConnectionString = connString
myConnection.Open()
Dim commandAdvComputer As New OleDbCommand("SELECT * FROM adv_computer", myConnection)
DRAdvComputer = commandAdvComputer.ExecuteReader()
Do WhileDRAdvComputer.Read
If DRAdvComputer.Item("emp_comp_amt") <> 0 And DRAdvComputer.Item("mont") <> 0 Then
nscd_emp_comp_adv = DRAdvComputer.Item("emp_comp_amt") / DRAdvComputer.Item("installment")
tempMontComputer = DRAdvComputer.Item("mont") - 2
cmdUpdateAdvCompu.CommandText = "UPDATE adv_computer SET mont = @mont WHERE emp_id = @ID"
cmdUpdateAdvCompu.Parameters.AddWithValue("@ID", DRAdvComputer.Item("emp_id"))
cmdUpdateAdvCompu.Parameters.AddWithValue("@mont", tempMontComputer)
cmdUpdateAdvCompu.CommandType = CommandType.Text
cmdUpdateAdvCompu.Connection = myConnection
cmdUpdateAdvCompu.ExecuteNonQuery()
End If
Loop
cmdUpdateCheckDate.Dispose()
cmdUpdateAdvCompu.Dispose()
myConnection.Close()
End Sub
答案 0 :(得分:0)
在OleDb中,参数不能通过名称识别,而是通过其位置识别
您可以在@ID
参数之前添加@mont
参数,因此在应用于参数占位符时会交换这两个值。这会给您一个不正确的查询,其中代码尝试使用@ID参数的值设置mont字段,并使用值@mont参数在WHERE语句中使用ID字段。因此,您不会更新任何内容,或者,对于偶然事件,您会更新错误的记录。
只需反转参数顺序:
Do WhileDRAdvComputer.Read
If DRAdvComputer.Item("emp_comp_amt") <> 0 And DRAdvComputer.Item("mont") <> 0 Then
nscd_emp_comp_adv = DRAdvComputer.Item("emp_comp_amt") / DRAdvComputer.Item("installment")
tempMontComputer = DRAdvComputer.Item("mont") - 2
cmdUpdateAdvCompu.CommandText = "UPDATE adv_computer SET mont = @mont WHERE emp_id = @ID"
cmdUpdateAdvCompu.Parameters.AddWithValue("@mont", tempMontComputer)
cmdUpdateAdvCompu.Parameters.AddWithValue("@ID", DRAdvComputer.Item("emp_id"))
cmdUpdateAdvCompu.CommandType = CommandType.Text
cmdUpdateAdvCompu.Connection = myConnection
cmdUpdateAdvCompu.ExecuteNonQuery()
End If
Loop