第一次张贴。我在这里享受了很多年的帮助。谢谢大家。
我的处境似乎无法实现。
在VS2017社区中使用VB.NET,我在Try块中获得了System.Data.ConstraintException,在该块中,我专门捕获了该确切异常。
消息显示如下:
System.Data.ConstraintException:'列'PAIR1,PAIR2,PAIR3'被限制为唯一。值'CHATBTC,ETHBTC,CHATETH'已经存在。'
https://www.dropbox.com/s/d91rgtwsjwioqhm/SO_error.jpg?dl=0
从逻辑上可以看出,我指望触发异常,这样我就可以构建一个唯一行表并将其添加到重复行值中。随着表格大小的增加,在ADD之前检查重复项会花费很多时间,因此这种方法是最快的。
它不会每次都发生,只有大约30%。我的应用程序尚无法在生产环境中运行,因此我看到的一切都是在调试时。
我的代码在这里:
tblTriArbPairs.PrimaryKey = New DataColumn() {tblTriArbPairs.Columns("PAIR1"), tblTriArbPairs.Columns("PAIR2"), tblTriArbPairs.Columns("PAIR3")}
Try
tblTriArbPairs.Rows.Add(
Pairs(0), Pairs(1), Pairs(2),
idxPair0, idxPair1, idxPair2,
result.TD1, result.TD2, result.TD3,
CoinOnly(Pairs(0)), CurrOnly(Pairs(0)),
CoinOnly(Pairs(1)), CurrOnly(Pairs(1)),
CoinOnly(Pairs(2)), CurrOnly(Pairs(2)),
FindLoopCoin(CoinOnly(Pairs(0)), CurrOnly(Pairs(0)), CoinOnly(Pairs(1)), CurrOnly(Pairs(1)), CoinOnly(Pairs(2)), CurrOnly(Pairs(2))),
GetSymbolLIQ(Pairs(0)), GetSymbolLIQ(Pairs(1)), GetSymbolLIQ(Pairs(2))
)
RowsAdded += 1
Catch ex As System.Data.ConstraintException
DupRows += 1
Catch ex As Exception
Finally
End Try
填充表格后,我最终添加了3480行和2640个重复项。错误发生的时间没有一致性。有时马上就到了,其他时候快要结束了。
我四处张望,没有找到解决未捕获ConstraintException的任何内容。其他例外,是的。
非常感谢您的帮助。希望我已经发布了一个很好的问题。 :)
答案 0 :(得分:0)
我已经读到,捕获异常是引导程序流的一种相当繁琐的方法,最好防止异常。
我认为这是您要处理的数据表,因此以下Linq可能会解决问题。根据docs“一旦确定结果,就会停止对源的枚举。”
我只是使用示例数据库进行测试。
Dim CoffeeName As String = "Black Tiger"
Dim CoffeeType = "Decaf"
Dim dup As Boolean = dt.AsEnumerable().Any(Function(Row) CoffeeName = Row.Field(Of String)("Name") And CoffeeType = Row.Field(Of String)("Type"))
MessageBox.Show(dup.ToString)
编辑 用您的变量和3个字段编写的代码。
Dim dup As Boolean = tblTriArbPairs.AsEnumerable().Any(Function(Row) Pairs(0) = Row.Field(Of String)("Pair1") _
And Pairs(1) = Row.Field(Of String)("Pair2") And Pairs(2) = Row.Field(Of String)("Pair3"))
If dup Then
DupRows += 1
MessageBox.Show("Sorry, duplicate")
Exit Sub
End If
'Add the row
答案 1 :(得分:0)
我从来没有解决过为什么抛出异常的问题,尽管我明确地将其困住了。我确实留意了这里的建议,以便在尝试将重复项添加到我的数据表之前检查是否存在重复项。这是我想出的,它似乎工作正常。
Dim iRow As DataRow() = tblTriArbPairs.Select("PAIR1 = '" & Pairs(0) & "' AND PAIR2 = '" & Pairs(1) & "' AND PAIR3 = '" & Pairs(2) & "'")
If iRow.Count = 0 Then
tblTriArbPairs.Rows.Add(
Pairs(0), Pairs(1), Pairs(2),
idxPair0, idxPair1, idxPair2,
result.TD1, result.TD2, result.TD3,
CoinOnly(Pairs(0)), CurrOnly(Pairs(0)),
CoinOnly(Pairs(1)), CurrOnly(Pairs(1)),
CoinOnly(Pairs(2)), CurrOnly(Pairs(2)),
FindLoopCoin(CoinOnly(Pairs(0)), CurrOnly(Pairs(0)), CoinOnly(Pairs(1)), CurrOnly(Pairs(1)), CoinOnly(Pairs(2)), CurrOnly(Pairs(2))),
GetSymbolLIQ(Pairs(0)), GetSymbolLIQ(Pairs(1)), GetSymbolLIQ(Pairs(2))
)
RowsAdded += 1
Else
DupRows += 1
End If
再次感谢所有提供帮助的人。我是通过第一个SO问题做到的!是的!