ms access 2010和vs2010如何连接

时间:2013-01-16 01:02:06

标签: visual-studio-2010 ms-access

cmd.ExecuteNonQuery()

中的程序崩溃
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

1 个答案:

答案 0 :(得分:0)

崩溃时是否正在运行INSERTUPDATE查询?

如果是INSERT查询,可能是因为SQL字符串最后有一个'

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

                       ^
                       here!

如果是UPDATE查询:如果Oznaka是字符串列,请将值放在引号中:

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

而不是

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

针对这两个问题的更好解决方案是:在查询中使用SQL参数而不是连接字符串。

以下是一些入门示例: