访问数据库不从vb.net更新

我有一个名为login.mdb的访问数据库,它有很多表。我想要更新名为“try”的表。我在表中我有两个字段viz名称和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 

请告诉我哪里mam错了。我得到错误:system.nullreferenceexception:对象引用未设置为对象的实例。

这里有几个问题:

  • “尝试”是某些数据库中的保留字。 访问是好的,但如果这一举动将导致问题。 最好早做好准备。
  • 没有查询参数(易受sql注入攻击)。 尝试input';DROP Table [Try];--在您的当前代码的文本框之一。
  • 全class通用的数据库连接可能会导致争用问题并成为瓶颈
  • 没有closuresfinally块中的连接,这可能会导致连接断开,最终甚至可能导致数据库不可用
  • 连接string中数据库的绝对path在部署时将失败
  • 从来没有创build连接对象的实例 (这是你的exception的错误)

你的代码应该看起来更像这样:

 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 

此代码解决了上面列出的所有问题,而不仅仅是导致当前exception的问题。

你在哪一行得到你的错误?

MyConnection1不看起来实例化(可能导致它)

; 在SQL的末尾是正确的?

也请尝试了解命令参数的概念。 像这样创buildsql只是显然是错误的。

 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 

这应该是更喜欢它:)