我收到以下错误
ExecuteNonQuery:尚未初始化Connection属性。
运行以下代码时
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Using con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = New OleDbCommand("UPDATE User-scores SET User_Name = @User_Name Game_Name = @Game_Name Score = @Score, [Time/Date] = @dt")
con.Open()
cmd.Parameters.Add("@User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("@Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("@Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("@dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
End Sub
我忘记在参数中添加一些内容吗?
答案 0 :(得分:1)
您必须将连接作为参数传递给OledbCommand
只需使用以下代码
Using con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = New OleDbCommand("UPDATE [User-scores] SET [User_Name] = ?, [Game_Name] = ?, Score = ?, [Time/Date] = ? WHERE id = 1", con)
con.Open()
cmd.Parameters.Add("@p1", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("@p2", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("@p3", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("@p4", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
看起来您必须使用?
标记将参数传递给OledbCommand
(您的方法适用于SQLCommand
)
详细了解Oledb Parameters
答案 1 :(得分:0)
您忘记添加命令连接,更新cmd,添加如下所示的连接
Using cmd = New OleDbCommand("UPDATE User-scores SET User_Name = @User_Name Game_Name = @Game_Name Score = @Score, [Time/Date] = @dt",con)
更新:更新COMMA更新
@User_Name, Game_Name = @Game_NamE, Score = @Score
答案 2 :(得分:0)
您尚未将命令与Connection相关联。代码不知道哪个连接(理论上你可能有几个)来运行命令。
您可以使用构造函数或属性将命令与特定连接相关联:
Using cmd = New OleDbCommand("UPDATE User-scores SET User_Name = @User_Name Game_Name = @Game_Name Score = @Score, [Time/Date] = @dt",con)
或者:
cmd.Connection = con
(在您声明cmd
后的行上)
答案 3 :(得分:0)
您可以使用CreateCommand创建连接创建命令。这样连接就已经与创建的命令相关联。但这意味着您必须在CommandText
属性
Using con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = con.CreateCommand()
con.Open()
cmd.CommandText = "UPDATE User-scores SET User_Name = @User_Name, Game_Name = @Game_Name, Score = @Score, [Time/Date] = @dt"
cmd.Parameters.Add("@User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("@Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("@Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("@dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using