我正在使用 VS 2010 同步 2 个数据库(SQL Express 和 SQL Compact Edition)。程序首次运行时它工作正常。但是,当代码执行多次时,会出现 SQL 命令“超时”异常。错误信息是:
超时已过。在操作完成之前超时时间已过或服务器没有响应。
以下是我处理ClientInsertServerInsert冲突的代码。(编辑:根据这篇 MSDN 文章,这与客户端和服务器都插入具有相同主键值的行有关。这会导致主键冲突。)
Dim conflictTableName As String = e.TableMetadata.TableName.ToString
Dim serverConflictDT, clientConflictDT As DataTable
Dim clientConflictID As Int16
Dim new_ID As Int16
Dim SqlCon As New SqlConnection
clientConflictDT = e.Conflict.ClientChange
serverConflictDT = e.Conflict.ServerChange
If e.Conflict.ConflictType = ConflictType.ClientInsertServerInsert Then
SqlCon = New SqlConnection(STR_SQL_CON)
Using SqlCon
If SqlCon.State = ConnectionState.Closed Then SqlCon.Open()
MsgBox(SqlCon.PacketSize.ToString & vbNewLine & conflictTableName.ToString)
Dim sqlStr = "SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName
Dim sqlcmd As New SqlCommand(sqlStr, SqlCon)
sqlcmd.CommandTimeout = 2
new_ID = sqlcmd.ExecuteScalar '<- This is the line where the Exception occurred
clientConflictID = clientConflictDT.Rows(0)(0)
MsgBox(new_ID.ToString & conflictTableName.ToString)
Try
Using SqlCeCon As New SqlCeConnection(STR_SQLCE_CON)
If SqlCeCon.State = ConnectionState.Closed Then SqlCeCon.Open()
Dim sqlCeCmd As New SqlCeCommand
Dim sqlCeStr = Nothing
sqlCeStr = "SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName
sqlCeCmd = New SqlCeCommand(sqlCeStr, SqlCeCon)
If new_ID < sqlCeCmd.ExecuteScalar Then
new_ID = sqlCeCmd.ExecuteScalar
End If
sqlCeStr = "UPDATE " & conflictTableName & " SET id=" & new_ID & " WHERE id=" & clientConflictID
sqlCeCmd.CommandText = sqlCeStr
sqlCeCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Finally
End Try
End Using
End If
提前致谢