[英]How can I check if a value pair already exists in the database?
In VB.Net, I am trying to check if a certain value pair already exists in the database. 在VB.Net中,我试图检查数据库中是否已存在某个值对。 If not, it needs to be added:
如果没有,则需要添加:
Public Shared Sub updateChoice(ByVal dbConn As NS.DBConn, ByVal Y As String, ByVal Z As Int32)
'check if the Y <=> Z pair already exists
Dim sqlText As String = "select from table where X = " & CStr(Y)" and Y =" &CStr(Z)
Dim pairExists = dbConn.ExecuteAsDataSet(sqlText)
If (pairExists <= 0) Then
Dim sqlText As String = "insert into table ..." ' Insert pair into DB
dbConn.ExecuteNonQuery(sqlText)
End If
End Sub
Visual Studio gives me an error on If (pairExists <= 0) Then
: Operator <= is not defined for types System.Data.DataSet and Integer
Visual Studio在
If (pairExists <= 0) Then
上给我一个错误: Operator <= is not defined for types System.Data.DataSet and Integer
I am having a hard time understanding this error. 我很难理解这个错误。 What am I doing wrong?
我究竟做错了什么?
It would be more efficient to do the check and the insert in the same statment, it also significantly reduces the chance of meeting a race condition by reducing the time between the check and the insert. 在同一条语句中执行检查和插入将更为有效,通过减少检查和插入之间的时间,也显着减少了满足比赛条件的机会。 The statement you would want is:
您想要的语句是:
MERGE Table WITH (HOLDLOCK) AS t
USING (VALUES (@X, @Y)) AS s (X, Y)
ON s.X = t.X
AND s.X = t.Y
WHEN NOT MATCHED THEN INSERT (X, Y) VALUES (X, Y)
OUTPUT $action;
Using MERGE
with HOLDLOCK
is the best way I know of to avoid a race condition, however it is not a substitute for a unique constraint. 我将
MERGE
与HOLDLOCK
一起使用是避免竞争情况的最佳方法,但是它不能替代唯一约束。 If the values should be unique in the table then this should still be enforced with a constraint. 如果值在表中应该是唯一的,则仍应使用约束来强制执行。 You can then simply check the return value of
ExecuteNonQuery()
, it will return 1 if a row is inserted, 0 if the pair already exists. 然后,您可以简单地检查
ExecuteNonQuery()
的返回值,如果插入一行,它将返回1,如果该对已经存在,则返回0。
You should also be using parameterised queries! 您还应该使用参数化查询!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.