vb.net DataGridView第二次删除出错,显示数据库连接关闭

xxuullboy1 2017-09-05 10:44:18
代码如下:
Imports System.Windows.Forms
Imports System.Data.SqlClient

Public Class FrmSpec
Inherits System.Windows.Forms.Form
Private Cn As SqlConnection
Private Da As SqlDataAdapter
Private Cmd As SqlCommand
Private Ds As DataSet
Private A As Integer
Private Sub FrmSpec_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
FrmMain.Enabled = True
FrmMain.Focus()
End Sub
Private Sub CheckCn()

End Sub
Private Sub FrmSpec_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Cn = New SqlConnection(cnStr)
If (Cn.State = ConnectionState.Closed) Then
Cn.Open()
End If
Sql = "select prdcom x1,x2,x3,x4 from pr1 "
Da = New SqlDataAdapter(Sql, Cn)
Ds = New DataSet()
Da.Fill(Ds, "prd")
Dim Bs As New BindingSource
Bs.DataSource = Ds.Tables("prd")
BdNtor1.BindingSource = Bs
DGView1.DataSource = Bs
With DGView1
.Columns(0).Width = 80
.Columns(1).Width = 70
.Columns(2).Width = 120
.Columns(3).Width = 130
End With
DGView1.Refresh()
Cn.Close()
End Sub
Private Sub DGView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGView1.CellClick
A = e.RowIndex
End Sub

Private Sub DelRec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DelRec.Click
If MessageBox.Show("你确定要删除这一笔资料?", "删除资料", MessageBoxButtons.OKCancel) = DialogResult.OK Then
Cn = New SqlConnection(cnStr)
If (Cn.State = ConnectionState.Closed) Then
Cn.Open()
End If
Sql = "DELETE FROM pr1 WHERE prdcode='" & DGView1.Rows(A).Cells(0).Value.ToString & "'"

Static Cmd As New SqlCommand(Sql, Cn)
Try
Cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Cn.Close()
End If

Call FrmSpec_Load(Nothing, Nothing)

End Sub
End Class

第一次删除正常,关闭后再删除也正常,但连续删除第二次提示,当前连接已关闭
请高手帮忙看下
...全文
406 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
1、看看业务需求,是否可以长连接,如果没什么问题,建议长连接大家都用。 2、如果涉及事物等,建议使用单次连接,操作完成提交后就断开,否则可能导致事物方面的各种混乱。 3、不管是哪种连接,你在数据库操作前判断一下连接是否在open状态,不是就尝试open他啊,就算不是你代码导致的断开,有人从数据库那边把你的长连接断开了你怎么办?重启程序吗?
轻鸿万里 2017-11-22
  • 打赏
  • 举报
回复
你直接在程序启动的时候打开了链接不要关闭链接就行了。以后不用经常打开关闭数据库连接。操作的时候直接执行SQL操作就行了
exception92 2017-10-26
  • 打赏
  • 举报
回复
http://www.cnblogs.com/alexis/archive/2010/11/06/1870519.html 调试你的程序,看第二次的Cn.State的值
FainSheeg 2017-10-26
  • 打赏
  • 举报
回复
Static Cmd As New SqlCommand(Sql, Cn) 不用Static试试。

16,552

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧