Executenonquery需要一个开放且可用的连接。连接当前状态已关闭

时间:2017-03-13 04:18:35

标签: vb.net ms-access

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim response As MsgBoxResult
        response = MsgBox("Do you want to save the data ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
        If response = MsgBoxResult.Yes Then
            Try
                Dim cm As New OleDb.OleDbCommand
                Dim cn As New OleDb.OleDbConnection
                cm = New OleDb.OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO Drug (DrugCode, DrugName, Branch Code, Branch Name, Dosage, UM, Quantity, Date, ConsPRN, EMPCode, EMPName, EMPPos) VALUES ('DCode', 'DName', 'BCode', 'BName')"

                    .Parameters.Add(New System.Data.OleDb.OleDbParameter("DCode", System.Data.OleDb.OleDbType.VarChar, 255, Me.DCode.Text))
                    .Parameters.Add(New System.Data.OleDb.OleDbParameter("DName", System.Data.OleDb.OleDbType.VarChar, 255, Me.DName.Text))
                    .Parameters.Add(New System.Data.OleDb.OleDbParameter("BCode", System.Data.OleDb.OleDbType.VarChar, 255, Me.BCode.Text))
                    .Parameters.Add(New System.Data.OleDb.OleDbParameter("BName", System.Data.OleDb.OleDbType.VarChar, 255, Me.BName.Text))


                    ' RUN THE COMMAND
                    cm.Parameters("DCode").Value = Me.DCode.Text
                    cm.Parameters("DName").Value = Me.DName.Text
                    cm.Parameters("BCode").Value = Me.BCode.Text
                    cm.Parameters("BName").Value = Me.BName.Text


                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    Me.DCode.Text = ""
                    Me.DName.Text = ""
                    Me.BCode.Text = ""
                    Me.BName.Text = ""
                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            Finally
            End Try
            ' MsgBox("Unable to save data. Please input blank fields!", MsgBoxStyle.Question + MsgBoxStyle.OkOnly, "Error")
        ElseIf response = MsgBoxResult.No Then
            Exit Sub
        End If
    End Sub

1 个答案:

答案 0 :(得分:0)

cn.Open()之前添加cm.ExecuteNonQuery,然后在退出子

之前添加cn.Close
cm.Parameters("DCode").Value = Me.DCode.Text
cm.Parameters("DName").Value = Me.DName.Text
cm.Parameters("BCode").Value = Me.BCode.Text
cm.Parameters("BName").Value = Me.BName.Text
cn.Open() '<----- open the connection
cm.ExecuteNonQuery()
cn.Close() '<--- close the conenction
MsgBox("Record saved.", MsgBoxStyle.Information)
Me.DCode.Text = ""
Me.DName.Text = ""
Me.BCode.Text = ""
Me.BName.Text = ""

另外,仔细检查您的cn oledb连接。它没有定义Connection String