473,748 Members | 2,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 strServerAddres s = "MyDbServer "
Private Const strDatabaseName = "MyDatabase "
Private Const strUserName = "MyUserName "
Private Const strPassword = "MyPassword "

Public Function genErrorColl(st rTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connectio n
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOL EDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password= " & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddres s & ";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.connectio n
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorT ype = adOpenKeyset
OpenRST.LockTyp e = adLockOptimisti c
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("v iewErrorCollect ion")

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 4444

"Jozef" <SP**********@t elus.net> wrote in message
news:yq2ze.1706 76$El.87155@pd7 tw1no...
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 strServerAddres s = "MyDbServer "
Private Const strDatabaseName = "MyDatabase "
Private Const strUserName = "MyUserName "
Private Const strPassword = "MyPassword "

Public Function genErrorColl(st rTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connectio n
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOL EDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password= " & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddres s & ";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.connectio n
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorT ype = adOpenKeyset
OpenRST.LockTyp e = adLockOptimisti c
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("v iewErrorCollect ion")

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.Connectio n

On Error GoTo Err_Handler

Dim strCnn As String
Dim blnError As Boolean
Dim cnn As ADODB.Connectio n

strCnn = "Provider=sqlol edb;" & _
"Data Source=MyServer ;" & _
"Initial Catalog=MyDatab ase;" & _
"User Id=MyUser;" & _
"Password=MyPas sword;"

Set cnn = New ADODB.Connectio n

cnn.ConnectionS tring = 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.Connectio n
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, adOpenForwardOn ly
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**********@t elus.net> wrote in message
news:yq2ze.1706 76$El.87155@pd7 tw1no...
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 strServerAddres s = "MyDbServer "
Private Const strDatabaseName = "MyDatabase "
Private Const strUserName = "MyUserName "
Private Const strPassword = "MyPassword "

Public Function genErrorColl(st rTableName As String) As ADODB.Recordset

Dim cnn1 As ADODB.connectio n
Dim strCnn As String
Dim varDate As Variant

' Open connection.
strCnn = "Provider=SQLOL EDB.1;Persist Security Info=False;User ID=" &
strUserName & ";password= " & strPassword & ";Initial Catalog=" &
strDatabaseName & ";Data Source=" & strServerAddres s & ";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.connectio n
cnn1.Open strCnn

' Open the Requested Table or View
Set OpenRST = New ADODB.Recordset
OpenRST.CursorT ype = adOpenKeyset
OpenRST.LockTyp e = adLockOptimisti c
OpenRST.Open strTableName, cnn1, , , adCmdTable
cnn1.Close
End Function

Private Sub testConn()
Dim rst As ADODB.Recordset

Set rst = genErrorColl("v iewErrorCollect ion")

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.Connectio n

On Error GoTo Err_Handler

Dim strCnn As String
Dim blnError As Boolean
Dim cnn As ADODB.Connectio n

strCnn = "Provider=sqlol edb;" & _
"Data Source=MyServer ;" & _
"Initial Catalog=MyDatab ase;" & _
"User Id=MyUser;" & _
"Password=MyPas sword;"

Set cnn = New ADODB.Connectio n

cnn.ConnectionS tring = 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.Connectio n
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, adOpenForwardOn ly
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
1858
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 contains methods for serialising and de-serialising objects to the database storage. I put this as a shared class as multiple web clients will be using the class to store and retreive data, the problem I'm haivng now is that I think multiple threads...
9
3081
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 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Declare your object variables
4
3842
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 session variables, the values are the actual column names and not the database value. I've tried using ordinal values and get the same results. --here's the code
7
2195
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 another. I have tried declaring them as shared, public, friend, etc and I always get an error stating that something is not valid on a local variable declaration. For example, in the following code for Sub DataGrid_Select, I have CurrentID and...
8
1488
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 state is Open, Fetching. at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method, Int32& localState) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at...
1
4358
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): req.content_type = 'text/plain' req.write("Under Construction")
0
5573
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 ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
17
46554
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: The goal of this tutorial is to design a Data Abstraction Layer (DAL) in PHP, that will allow us to ignore the intricacies of MySQL and focus our attention on our Application Layer and Business Logic. Hopefully, by the end of this guide, you will...
0
3192
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 fine. Now we decided to move from mainframe IMS-DB2 to Windows 2003 server-DB2 UDB for LUW 9.5.
0
8991
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
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
8245
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
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
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
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
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.