2013-01-16 92 views
0

程序崩潰的cmd.ExecuteNonQuery()的MS Access 2010和VS2010如何連接

Public Class Form1 
    Dim conn As New OleDb.OleDbConnection 
    Private Sub RefreshData() 
     If Not conn.State = ConnectionState.Open Then 
      'open connection 
      conn.Open() 
     End If 

     Dim da As New OleDb.OleDbDataAdapter("SELECT Oznaka as [Oznaka], " & _ 
              "ReN as [ReN], RmN " & _ 
              " FROM Tabela ORDER BY Oznaka", conn) 
     Dim dt As New DataTable 
     'fill data to datatable 
     da.Fill(dt) 

     'offer data in data table into datagridview 
     Me.DataGridView1.DataSource = dt 

     'close connection 
     conn.Close() 
    End Sub 


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim cmd As New OleDb.OleDbCommand 
     If Not conn.State = ConnectionState.Open Then 
      'open connection if it is not yet open 
      conn.Open() 
     End If 

     cmd.Connection = conn 
     'check whether add new or update 
     If Me.txtOznaka.Tag & "" = "" Then 
      'add new 
      'add data to table 
      cmd.CommandText = "INSERT INTO Tabela(Oznaka, ReN, RmN) " & _ 
           " VALUES('" & Me.txtOznaka.Text & "','" & Me.txtReN.Text & "','" & _ 
           Me.txtRmN.Text & "'')" 

      cmd.ExecuteNonQuery() 
     Else 
      'update data in table 
      cmd.CommandText = "UPDATE Tabela " & _ 
         " SET Oznaka=" & Me.txtOznaka.Text & _ 
         ", ReN='" & Me.txtReN.Text & "'" & _ 
         ", RmN='" & Me.txtRmN.Text & "'" & _ 
            " WHERE Oznaka=" & Me.txtOznaka.Tag 
      cmd.ExecuteNonQuery() 

     End If 
     'refresh data in list 
     RefreshData() 
     'clear form 
     'Me.btnClear.PerformClick() 

     'close connection 
     conn.Close() 

    End Sub 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     conn = New OleDb.OleDbConnection 
     conn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\baza.mdb" 
     ' 
     'get data into list 
     Me.RefreshData() 
    End Sub 



End Class 

回答

0

你運行的INSERTUPDATE查詢時崩潰?

如果它是INSERT查詢,這可能是因爲SQL字符串有一個'末太多:

... Me.txtRmN.Text & "'')" 

        ^
         here! 

如果它是UPDATE查詢:如果Oznaka是字符串列,加上引號值而不是

" SET Oznaka='" & Me.txtOznaka.Text & "'" & _ 

" SET Oznaka=" & Me.txtOznaka.Text & _ 

對於這兩個問題,更好的解決方案是:在查詢中使用SQL參數而不是串聯字符串。

下面是一些例子開始: