473,796 Members | 2,537 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is it necessary to close a local OleDbDataReader before exit function?

Hi, everybody,

The codes below run under VS2003 for a long time. I want to upgrade it to VS2005. VS2005 gives me some varning messages such as "Varibles shouldn't be used before being assigned".

My question is: Is it necessary to close sDa in my code?

'-------------------------------------------------------------------------------
Private Function MethodIDExist(B yVal iMethodID As Integer) As Boolean
Dim oCmd As New OleDbCommand

If ConnMethod.Stat e = ConnectionState .Closed Then ConnMethod.Open ()
With oCmd
.Connection = ConnMethod
.CommandType = CommandType.Sto redProcedure
.CommandText = "StoredProcedur eName"

.Parameters.Add ("", OleDbType.Integ er)
.Parameters(0). Value = iMethodID
End With

Dim sDa As OleDbDataReader

Try

sDa = oCmd.ExecuteRea der()
If sDa.Read() Then
Dim Num As Integer = sDa(0)
If Num 0 Then
sDa.Close()
Return True
End If
End If
If Not sDa.IsClosed Then sDa.Close()
Return False
Catch exc As Exception
MessageBox.Show (exc.ToString)
'************** *************** *************** *************** **********
If (Not sDa Is Nothing) AndAlso (Not sDa.IsClosed) Then sDa.Close()
'************** *************** *************** *************** **********
Return False
End Try
End Function
'--------------------------------------------------------------------------------

Thanks in advance,

Peter
Dec 26 '06 #1
2 1242
Regardless of whether or not you are exiting from a method, you should
ALWAYS close a DataReader as soon as possible after you are finished using
it.

In my opinion the method is making hard work of something that is very
simple.

If, as the logic shows, you are only interested in the value from the first
column of the first row returned by the strored procedure, then you have no
need to use a DataReader at all. The ExecuteScalar() method of the
OleDbCommand object will do the job, in conjunction with a type conversion
and a test resulting in a boolean result.

Return (CType(oCmd.Exe cuteScalar(), Integer) 0)

Doing away with the DataReader object will stop the warning message from
being generated

Note too that there is an overload of the constructor for the OleDbCommand
object that takes commandtext and connection parameters. This means that you
do not have to set all the properties of the OleDbCommand object seperately.
You do, however, need to set the CommandType property seperately.

In addition, you can add the parameter object and set it's value in a single
statemment.

I note that you are 'opening' the connection object if it is not already
open and leaving it open. If that is your intention then well and good. If
however, you intend to leave it in the state you found it, then you need to
keep track of it's state and close it if you opened it in this method.

The 'improved' method would be something like:

Private Function MethodIDExist(B yVal iMethodID As Integer) As Boolean

' Save the current state of the connection
Dim _constate as ConnectionState = ConnMethod.Stat e

If _constate = ConnectionState .Closed Then ConnMethod.Open ()

Dim oCmd As New OleDbCommand("S toredProcedureN ame", ConnMethod)

oCmd.CommandTyp e = CommandType.Sto redProcedure

oCmd.Parameters .Add("", OleDbType.Integ er).Value = iMethodID

Try
Return (CType(oCmd.Exe cuteScalar(), Integer) 0)
Catch exc As Exception
MessageBox.Show (exc.ToString)
Return False
Finally
' If the connection was closed to start with then close it here
If _constate = ConnectionState .Closed Then ConnMethod.Clos e()
End Try

End Function
"Peter" <zl*****@sina.c omwrote in message
news:uN******** ******@TK2MSFTN GP03.phx.gbl...
Hi, everybody,

The codes below run under VS2003 for a long time. I want to upgrade it to
VS2005. VS2005 gives me some varning messages such as "Varibles shouldn't be
used before being assigned".

My question is: Is it necessary to close sDa in my code?

'-------------------------------------------------------------------------------
Private Function MethodIDExist(B yVal iMethodID As Integer) As Boolean
Dim oCmd As New OleDbCommand

If ConnMethod.Stat e = ConnectionState .Closed Then ConnMethod.Open ()
With oCmd
.Connection = ConnMethod
.CommandType = CommandType.Sto redProcedure
.CommandText = "StoredProcedur eName"

.Parameters.Add ("", OleDbType.Integ er)
.Parameters(0). Value = iMethodID
End With

Dim sDa As OleDbDataReader

Try

sDa = oCmd.ExecuteRea der()
If sDa.Read() Then
Dim Num As Integer = sDa(0)
If Num 0 Then
sDa.Close()
Return True
End If
End If
If Not sDa.IsClosed Then sDa.Close()
Return False
Catch exc As Exception
MessageBox.Show (exc.ToString)
'************** *************** *************** *************** **********
If (Not sDa Is Nothing) AndAlso (Not sDa.IsClosed) Then
sDa.Close()
'************** *************** *************** *************** **********
Return False
End Try
End Function
'--------------------------------------------------------------------------------

Thanks in advance,

Peter
Dec 26 '06 #2
Thank you very much, Stephany. I really need to do much to improve my old
codes.

Peter

Dec 26 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
25032
by: Andras Gilicz | last post by:
Hi VB fans I'm working on a relatively large project in VB6 with about a dozen forms, including graphs, labels, text boxes, etc. The software itself is actually a flow simulator with more or less complex technical calculations, several input variables. I would like to equipp the starting panel with the usual New, Open, Save, Save As, Close etc. menus (like in Excel, or Word, etc.) What is the best way to accomplish Save, or Save As?...
1
5567
by: Gary Cobden | last post by:
Hi I have a routine that uses VBA to open a hidden occurence of Excel, and do background computations. However, in the event that the routine terminates abnormally, I have not been able to find a way of closing this Hidden occurrence. I can close any foreground instances without any problem, but the same coding does not work for hidden occurences.
4
1424
by: James Birkholz via AccessMonster.com | last post by:
A few months ago, a working Access97 system started exhibiting this behavior. About half the time when the .mde is closed, the app window remains open and can then only be closed by using "End task" from Task Manager, or sometimes a right click "Close" will work on the button on the Task Bar (but only on W2K stations, as opposed to NT stations, I think). Ideas? -- Message posted via http://www.accessmonster.com
1
1844
by: Ebrahim | last post by:
This message is in reply to a prev 1 . My application refues to close . Some one had suggested that I might have threads running.. but i solved that problem too . The app still refuses to close . !! Here is the code for one of them !! I call a stop function to disconnect all objects (close ) . I also make a call to Stop in the Dispose() function .
4
6739
by: rs | last post by:
how I the client tell the server that the socket is closed? or this there an even that informs the server that the clients socket is close? Oh, I am using vb.net 2003 Thanks
5
2060
by: Varangian | last post by:
Hello there people, I'm having some kind of problem. I have a function that returns a datareader. At some point using the application I get an error "Unspecified error" (ssssoooo helpful) :). I think I know the problem. My Connection remains open. Is there a way I can do to close the Connection. below is the code. Thank you very much as always
2
2951
by: jpr | last post by:
I am using moduled to open forms. I run them from a menu that I have created on the toolbar. The source of the forms are queries all with record source to "lstpreinterview" on a form named eforms. Public Function Openmyform() If IsNull(Forms!eforms!lstPreInterview) Then MsgBox "Sorry. You need to select a record!" Exit Function Else
3
1699
by: Bob | last post by:
I need to get several recordset for which I'm opening a datareader like so... OleDbCommand rsA = new OleDbCommand("Select * from Authors",cnAccess); OleDbDataReader drA = rsA.ExecuteReader(); while(drA.Read()) { sbL.Append("<tr><td>"+drA.ToString()+"</td></tr>"); }
32
2366
by: Andy | last post by:
To further follow up on my last post regarding the docmd.quit vs. Application.quit using access 2007, I noticed that docmd.quit will correctly compact the database (program file) if you have the "Compact on Close" option set for the current database. However, even with Compact on Close set, if you use the Application.Quit acQuitSaveNone, the compacting will not fire. This behavior actually seems desirable, as you can now make a program...
0
9529
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10457
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7550
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4119
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.