我试图将文本框中的记录更新到Access数据库中,我想知道每次点击保存时都会产生错误
未处理的类型' System.Data.OleDb.OleDbException'发生在System.Data.dll
中附加信息:没有给出一个或多个必需参数的值。
突出显示.ExecuteNonQuery()
这是什么意思?它阻止我运行我的代码:(
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=empFname, LastName=empLname, Department=empDept, " & _
"Status=empStat, Years=empYears " & _
"WHERE empID=empNum"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
Using cmd2 = New OleDbCommand(sqlQuery, con)
cmd.Parameters.AddWithValue("FirstName", empFname)
cmd.Parameters.AddWithValue("LastName", empLname)
cmd.Parameters.AddWithValue("Department", empDept)
cmd.Parameters.AddWithValue("Status", empStat)
cmd.Parameters.AddWithValue("Years", empYears)
cmd.ExecuteNonQuery()
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub
答案 0 :(得分:1)
您正在尝试为适配器的SelectCommand设置UPDATE命令文本。这当然无法取得成功。最后但并非最不重要的是,UPDATE命令文本不包含WHERE子句,因此,如果执行,它将使用相同的数据更新表tbl_empinfo中的每条记录。
在此上下文中,不需要使用适配器。您可以简单地执行命令,提供适当的WHERE子句和其他参数的值
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=?, LastName=?, Department=?, " & _
"Status=?, Years=? " & _
"WHERE empID=?"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("@p1", empFName)
.Parameters.AddWithValue("@p2", empLName)
.Parameters.AddWithValue("@p3", empDept)
.Parameters.AddWithValue("@p4", empStat)
.Parameters.AddWithValue("@p5", empYears)
.Parameters.AddWithValue("@p6", empNum)
.ExecuteNonQuery()
End With
在此之后,您可以调用重新加载数据的代码来填充网格
sqlQuery = "SELECT * FROM tbl_empinfo"
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim Table As New DataTable
With cmd1
.CommandText = sqlQuery
.Connection = con
With da
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
请注意,我已将命令和适配器的名称更改为较少混淆的名称。 SqlCommand和SqlDataAdapter是等同于OleDbCommand和OleDbDataAdapter但用于Sql Server的类的名称。乍一看,我以为您正在尝试使用SqlClient类来更新MS-Access数据库。