大家如何处理连接突然中断的问题
在C/S程序中,读写数据库的操作是非常频繁的,往往正在进行某一操作时,连接突然中断了,就会出现异常。单单就某一过程(或操作)处理这种异常是很容易做到,但是整个程序中有那么多的过程,难道每个需要的地方都要做这种判断吗?应该怎么处理?
[解决办法]
google aop 异常拦截
[解决办法]
C/S复杂操作要使用事务对DB进行操作,突然中断要事务回滚,事务可以嵌套,回滚一下就全部回滚,建议你做几个小实验九明白了
[解决办法]
成组的数据库操作用事务,这是最基本的规则了。
毕竟允许中间任何步骤中断后不需回滚的业务非常罕见。
正好用 MSDN 帮助中的例子说明
Public Sub RunSqlTransaction(myConnString As String)
Dim myConnection As New SqlConnection(myConnString)
myConnection.Open()
Dim myTrans As SqlTransaction
myTrans = myConnection.BeginTransaction("SampleTransaction")'启动事务'
Try
操作1
操作2
。。。
操作m
myTrans.Commit()'所有操作都没出错,可以递交事务了。'
Console.WriteLine("Both records are written to database.")
Catch e As Exception
Try
myTrans.Rollback("SampleTransaction")'如果连接还在,客户端发起回滚'
Catch ex As SqlException
If Not myTrans.Connection Is Nothing Then
'如果连接断了,数据库在超时后也会自动回滚。'
Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
'显示必要的出错提示'
Console.WriteLine("An exception of type " & e.GetType().ToString() & _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub 'RunSqlTransaction