473,398 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Help creating connection function

Hello,

I'm trying to create a central function that runs a connection to an SQL
Server database. The connection etc works, but when I try to call it, I get
an error saying "Runtime-Error 91: Object variable or with block variable
not set". I have pasted the code below. The first section is the function
that I'm using, the second function is only the test that calls teh
genErrorColl function
'***************** Start Code
***********************************************
Private Const strServerAddress = "MyDbServer"
Private Const strDatabaseName = "MyDatabase"
Private Const strUserName = "MyUserName"
Private Const strPassword = "MyPassword"

Public Function genErrorColl(strTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connection
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password=" & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddress & ";Use Procedure for
Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for
Data=False;Tag with column collation when possible=False"
Set cnn1 = New ADODB.connection
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorType = adOpenKeyset
OpenRST.LockType = adLockOptimistic
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("viewErrorCollection")

Do While Not rst.EOF
Debug.Print rst!kErrorLogID
rst.MoveNext
Loop

End Sub
'************* End of Code ************************************

Any help would be great.

Thanks!
Nov 13 '05 #1
2 4409

"Jozef" <SP**********@telus.net> wrote in message
news:yq2ze.170676$El.87155@pd7tw1no...
Hello,

I'm trying to create a central function that runs a connection to an SQL
Server database. The connection etc works, but when I try to call it, I
get an error saying "Runtime-Error 91: Object variable or with block
variable not set". I have pasted the code below. The first section is
the function that I'm using, the second function is only the test that
calls teh genErrorColl function
'***************** Start Code
***********************************************
Private Const strServerAddress = "MyDbServer"
Private Const strDatabaseName = "MyDatabase"
Private Const strUserName = "MyUserName"
Private Const strPassword = "MyPassword"

Public Function genErrorColl(strTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connection
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password=" & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddress & ";Use Procedure for
Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for
Data=False;Tag with column collation when possible=False"
Set cnn1 = New ADODB.connection
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorType = adOpenKeyset
OpenRST.LockType = adLockOptimistic
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("viewErrorCollection")

Do While Not rst.EOF
Debug.Print rst!kErrorLogID
rst.MoveNext
Loop

End Sub
'************* End of Code ************************************

Any help would be great.

Thanks!

Your function genErrorColl is supposed to return a recordset, but I don't
see it doing it anywhere - it doesn;t seem to return anything. I can't see
that you've dimmed OpenRST - does this mean you are not using Option
Explicit to ensure your variables are dimensioned. You also close the
connection, before you have used the recordset.

If I were you, I would separate the code which gets a connection to the part
which gets a recordset. Although, there are any number of ways you could
structure your code, the first function might prove useful to re-use -it
either returns a database connection or returns nothing, allowing you to
give your users a non-nerdy error message.
Function DbConnection() As ADODB.Connection

On Error GoTo Err_Handler

Dim strCnn As String
Dim blnError As Boolean
Dim cnn As ADODB.Connection

strCnn = "Provider=sqloledb;" & _
"Data Source=MyServer;" & _
"Initial Catalog=MyDatabase;" & _
"User Id=MyUser;" & _
"Password=MyPassword;"

Set cnn = New ADODB.Connection

cnn.ConnectionString = strCnn

cnn.Open

Exit_Handler:

If blnError Then
Set cnn = Nothing
End If

Set DbConnection = cnn

Exit Function

Err_Handler:
blnError = True ' No error message here
Resume Exit_Handler

End Function

Public Sub TestConnection()

On Error GoTo Err_Handler

Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset

Set cnn = DbConnection()

If Not cnn Is Nothing Then
Set rst = New ADODB.Recordset
rst.Open "SELECT COUNT(*) FROM tblLogins", cnn, adOpenForwardOnly
While Not rst.EOF
MsgBox rst.Fields(0)
rst.MoveNext
Wend
Else
MsgBox "Cannot establish a database connection", vbCritical
End If

Exit_Handler:

On Error Resume Next

If Not rst Is Nothing Then
rst.Close
Set rst = Nothing
End If

If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If

Exit Sub

Err_Handler:
MsgBox Err.Description, vbExclamation, "Error No: " & Err.Number
Resume Exit_Handler

End Sub


Nov 13 '05 #2
DOH!

Thanks Justin....Never code when you're tired and having a glass of wine. I
had changed the name of the function, but obviously didn't check the rest of
it.

Thanks for the pointers on splitting it up. I usually try to do that in a
round about way, get the thing working first, then try and break it apart
(the original code had everything together, connection, record set, setting
new record, updating database) and this is my first step, pulling the
connection and record set items out into separate functions.

Thanks for your help!
"Justin Hoffman" <j@b.com> wrote in message
news:da**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com...

"Jozef" <SP**********@telus.net> wrote in message
news:yq2ze.170676$El.87155@pd7tw1no...
Hello,

I'm trying to create a central function that runs a connection to an SQL
Server database. The connection etc works, but when I try to call it, I
get an error saying "Runtime-Error 91: Object variable or with block
variable not set". I have pasted the code below. The first section is
the function that I'm using, the second function is only the test that
calls teh genErrorColl function
'***************** Start Code
***********************************************
Private Const strServerAddress = "MyDbServer"
Private Const strDatabaseName = "MyDatabase"
Private Const strUserName = "MyUserName"
Private Const strPassword = "MyPassword"

Public Function genErrorColl(strTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connection
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password=" & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddress & ";Use Procedure
for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for
Data=False;Tag with column collation when possible=False"
Set cnn1 = New ADODB.connection
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorType = adOpenKeyset
OpenRST.LockType = adLockOptimistic
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("viewErrorCollection")

Do While Not rst.EOF
Debug.Print rst!kErrorLogID
rst.MoveNext
Loop

End Sub
'************* End of Code ************************************

Any help would be great.

Thanks!

Your function genErrorColl is supposed to return a recordset, but I don't
see it doing it anywhere - it doesn;t seem to return anything. I can't
see that you've dimmed OpenRST - does this mean you are not using Option
Explicit to ensure your variables are dimensioned. You also close the
connection, before you have used the recordset.

If I were you, I would separate the code which gets a connection to the
part which gets a recordset. Although, there are any number of ways you
could structure your code, the first function might prove useful to
re-use -it either returns a database connection or returns nothing,
allowing you to give your users a non-nerdy error message.
Function DbConnection() As ADODB.Connection

On Error GoTo Err_Handler

Dim strCnn As String
Dim blnError As Boolean
Dim cnn As ADODB.Connection

strCnn = "Provider=sqloledb;" & _
"Data Source=MyServer;" & _
"Initial Catalog=MyDatabase;" & _
"User Id=MyUser;" & _
"Password=MyPassword;"

Set cnn = New ADODB.Connection

cnn.ConnectionString = strCnn

cnn.Open

Exit_Handler:

If blnError Then
Set cnn = Nothing
End If

Set DbConnection = cnn

Exit Function

Err_Handler:
blnError = True ' No error message here
Resume Exit_Handler

End Function

Public Sub TestConnection()

On Error GoTo Err_Handler

Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset

Set cnn = DbConnection()

If Not cnn Is Nothing Then
Set rst = New ADODB.Recordset
rst.Open "SELECT COUNT(*) FROM tblLogins", cnn, adOpenForwardOnly
While Not rst.EOF
MsgBox rst.Fields(0)
rst.MoveNext
Wend
Else
MsgBox "Cannot establish a database connection", vbCritical
End If

Exit_Handler:

On Error Resume Next

If Not rst Is Nothing Then
rst.Close
Set rst = Nothing
End If

If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If

Exit Sub

Err_Handler:
MsgBox Err.Description, vbExclamation, "Error No: " & Err.Number
Resume Exit_Handler

End Sub

Nov 13 '05 #3

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

Similar topics

6
by: Paul | last post by:
Hi. Just trying to find out the best approach as I beleive it might give me problems later on down the road. I have an ASP.NET application which references a shared database class which...
9
by: Patrick.O.Ige | last post by:
I have a code below and its a PIE & BAR CHART. The values now are all static but I want to be able to pull the values from a database. Can you guys give me some ideas to do this? Thanks ...
4
by: Rob | last post by:
Hi, I've been going at this for a few days and can't see the problem. Does anyone see a problem with this code? I have a call to a function that returns a dataset and when I assign values to...
7
by: Aaron | last post by:
Complete code follows. I am new to .NET programming (and programming in general) and I am having a difficult time understanding how to fill a variable in one sub, and then access it from...
8
by: santosh singh via DotNetMonster.com | last post by:
Hi, I'm new to VB.NET..I'm developing a login page...im getting this error.. System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current...
1
by: treelife | last post by:
I'm getting and internal server error when | run the following mod_python script. I am actually trying to run Django. Script: from mod_python import apache def handler(req):...
0
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted...
17
Motoma
by: Motoma | last post by:
This article is cross posted from my personal blog. You can find the original article, in all its splendor, at http://motomastyle.com/creating-a-mysql-data-abstraction-layer-in-php/. Introduction:...
0
by: SOI_0152 | last post by:
Hi all! Happy New Year 2008. Il hope it will bring you love and happyness I'm new on this forum. I wrote a stored procedure on mainframe using DB2 7.1.1 and IBM language c. Everything works...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...

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.