我正在尝试使用SQL查询更新Access数据库,每当我单击“保存”按钮时,它都会生成错误
System.Data.dll中出现未处理的“System.Data.OleDb.OleDbException”类型异常
附加信息:没有给出一个或多个必需参数的值。
并突出显示.ExecuteNonQuery()
。你能帮助我吗?我是vb.net的新手。
提前致谢。
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()
MsgBox(empNum)
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo SET EmpID='" & empNum & "', FirstName ='" & empFname & "', LastName='" & empLname & "', Department='" & empDept & "', Status='" & empStat & "', Years='" & empYears & "' WHERE EmpID ='" & empNum & "' "
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
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 :(得分:2)
您的查询语法错误。由于您正在使用params,因此在SQL中使用占位符:(问号不是某些'类型的东西,您使用?
来标记参数!):
Dim sqlQuery As String = "UPDATE tbl_empinfo SET FirstName = ?,
LastName=?, Department=?,
Status=?, Years=? WHERE empID = ?"
注意:六个参数
' USING will dispose of the cmd when it is done with it
' ...can also set the SQL and connection props in the constructor:
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
' no reason to move Textboxes to a variable either:
.Parameters.AddWithValue("@p1", empFnameText.Text)
.Parameters.AddWithValue("@p2", empLnameText.Text)
.Parameters.AddWithValue("@p3", DeptText.Text)
.Parameters.AddWithValue("@p4", StatText.Text)
.Parameters.AddWithValue("@p5", yearstext.Text)
你缺少的第6个参数:
.Parameters.AddWithValue("@p6", eNumText.Text)
.ExecuteNonQuery()
End With
End Using
我认为Access不支持命名参数,因此您使用虚拟参数,但请确保{SQL}字符串中指定的顺序为AddWithValue
。
修改强>
您可以创建一个嵌入值的SQL字符串,而不是使用params,它是 sort 您的SQL字符串的作用。参数更好(研究SQL注入攻击),但你的字符串方法是错误的(你不能混合方法)。它应该是:
Dim sqlQuery As String = "UPDATE tbl_empinfo " &
"SET FirstName = " & empFname & ", LastName=" & empLname
变量必须在引号之外,否则您将FirstName
设置为文字" empFname"