简体   繁体   中英

C# Equivalent of adodb recordsets

I am converting a VB6 windows application to C# using VS2008, V3.5. I have a SQL Server 2000 database I use for data storage and retrieval. One table holds a single record that is of type Int and is used for generating a quote number, ie, 123456. In VB6 I do the following:

OpenDBCon
Set rst = New ADODB.Recordset
rst.Open "SELECT idx From tblQuoteIdx", cn, adOpenDynamic, adLockPessimistic
Select Case rst.BOF
Case False
    rst.MoveFirst
        Me.txtRef = rst!idx
        tID = rst!idx + 1
    OKToContinue = True
Case False
    'Do something
End Select

If OKToContinue = True Then
  Set rst = New ADODB.Recordset
  rst.Open "update tblQuoteIdx set idx = '" & tID & "' ", cn, adOpenDynamic, 
    adLockPessimistic
End If
CloseDBCon

In C# I currently am doing this:

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = Vars.connstring;
        conn.Open();
        SqlCommand sqlComm = new SqlCommand("Select idx from tblQuoteIdx", conn);
        Int32 tt = (Int32)sqlComm.ExecuteScalar();
        Int32 tt2 = tt++;
        SqlCommand sqlComm2 = new SqlCommand("Update tblQuoteIdx set " +
         "idx = " + tt2    + "", conn);
        sqlComm.ExecuteNonQuery();
        conn.Close();

Unfortunately I find now without a cursor lock of "adLockPessimistic" when several people hit the record at the same time multiple instances of the same index number can show up. If anyone could either explain how to use an ADODB.Recordset in C# for this specific purpose and or use record locks so as to lock the db record when needed, OR a better way within the .Net framework and C# principals to accomplish the same thing, I would be greatful. Many thanks in advance.

Noel

I believe you will find this article useful: Pessimistic locking in ado.net Basically you will need to wrap everything in a transaction that applies a lock on the records as soon as editing starts. This way no other method will be able to edit the values until the lock is released.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM