我有一个名为login.mdb的访问数据库,它有很多table.i想要更新名为“try”的表。在tat表中我有两个字段即名称和rollnumber.i想要更新相应name.my的rollnum代码是:
Public Class Form11
Inherits System.Windows.Forms.Form
Dim MyConnection1 As System.Data.OleDb.OleDbConnection
Dim myCommand1 As New System.Data.OleDb.OleDbCommand
Dim sql As String
''# ....
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
MyConnection1.ConnectionString = "PROVIDER=Microsoft.JET.OLEDB.4.0;Data Source = C:\Documents and Settings\1001\Desktop\Subhedar Sir\WindowsApplication1\bin\login.mdb"
MyConnection1.Open()
myCommand1.Connection = MyConnection1
myCommand1.CommandText = "UPDATE try SET rollnumber = '" & TextBox1.Text & "' WHERE nam = '" & TextBox2.Text & "';"
myCommand1.CommandType = CommandType.Text
myCommand1.Connection = MyConnection1
myCommand1.ExecuteNonQuery()
MsgBox("done")
MyConnection1.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
请告诉我哪里出错了。我收到错误: system.nullreferenceexception:对象引用未设置为对象的实例。
答案 0 :(得分:2)
你在哪一行收到错误?
MyConnection1看起来并不是真实的(可能导致它)
在SQL的末尾是正确的吗?
另请尝试了解命令参数的概念。像这样创建sql是完全错误的。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using MyConnection1 As New System.Data.OleDb.OleDbConnection("PROVIDER=Microsoft.JET.OLEDB.4.0;Data Source = C:\Documents and ings\1001\Desktop\Subhedar Sir\WindowsApplication1\bin\login.mdb"), _
myCommand1 As New System.Data.OleDb.OleDbCommand("UPDATE try SET rollnumber = @rollnumber WHERE nam = @nam", MyConnection1)
myCommand1.Parameters.AddWithValue("@rollnumber", TextBox1.Text)
myCommand1.Parameters.AddWithValue("@nam", TextBox2.Text)
MyConnection1.Open()
myCommand1.ExecuteNonQuery()
MsgBox("done")
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
这应该更像它:)
答案 1 :(得分:2)
这里有几个问题:
';DROP Table [Try];--
。您的代码看起来应该更像这样:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using cn As New OleDbConnection("PROVIDER=Microsoft.JET.OLEDB.4.0;Data Source = login.mdb"), _
cmd As New OleDbCommand("UPDATE [try] SET rollnumber= ? WHERE nam= ? ;", cn)
''# Note: I normally don't use AddWithValue(), but I don't know your data types
cmd.Parameters.AddWithValue("?", TextBox1.Text)
cmd.Parameters.AddWithValue("?", TextBox2.Text)
Try
cn.Open()
cmd.ExecuteNonQuery()
MsgBox("done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Sub
此代码解释了上面列出的问题的所有,而不仅仅是造成当前异常的问题。