Windows Tech Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 17 November 2011

Don't Forget the Eggs: ADO basic errors

Posted on 17:13 by Unknown
I'm not a DBA, although I play one on breaks in the kitchen at work.  I have worked with various databases for quite a few years, including MS SQL Server, MySQL, and Oracle.  I don't count FoxPro or Access because I absolutely hate client-side databases due to the bullshit headaches they create for IT departments (and consultants like myself), but alas, I have already digressed on that subject in previous blog posts.

One thing I see quite a bit with ADO examples in particular is a lack of (a) error checking and (b) connection limiting.  I'm not talking about connection throttling, but rather: applying some refactoring logic to how you open and close connections to optimize the use of the open pipeline without keeping it open too long (or re-opening it too many times).

As for error checking:  This is a fairly standard/typical piece of VBscript/ASP code for running a "select" query via ADO against a database.  It doesn't matter whether that database is local to the server/host where the code is being executed, well, it does actually, it matters more if it's remote, but whatever, let's chew and digest slowly here...

[CODE]
Set conn = Server.CreateObject("ADODB.Connection")
Set cmd = Server.CreateObject("ADODB.Command")
Set rs = Server.CreateObject("ADODB.Recordset")

query = "SELECT * FROM dbo.SomeTable WHERE id=" & _
idNumber & " ORDER BY ItemName"

conn.Open dsnString

rs.CursorLocation = adUseClient
rs.CursorType = adOpenStatic
rs.LockType = adLockReadOnly

Set cmd.ActiveConnection = conn

cmd.CommandType = adCmdText
cmd.CommandText = query
rs.Open cmd

If Not(rs.BOF And rs.EOF) Then
cols = rs.Fields.Count
rows = rs.RecordCount
Do Until rs.EOF
' do something stupid here
rs.MoveNext
Loop
Else
    Response.Write "oops, no records were returned"
End If

rs.Close
conn.Close
Set rs = Nothing
Set cmd = Nothing
Set conn = Nothing
[/CODE]

This looks simple enough. But there are quite a few places that could implode here if not handled explicitly.  Granted, error handling with .NET is more robust, but indulge me here for a moment since (A) there's still 100 times more VBScript code strewn about this planet than .NET code, and (B) I'm old.  The big three problems that are most likely to occur with this scenario are...

Connection Failure
Connection Delay / Time-Out
Recordset Access Failure (access denied)

Let's handle them one by one...

Connection Failure

Prior to the "conn.Open" statement, we should override the default error system and then check for the exit code from the .Open method and see what happened.  If it was successful (exit code: 0), we continue on, otherwise we should handle the error and exit safely.


[CODE]
On Error Resume Next
conn.Open dsnString
If err.Number <> 0 Then
    ' an error occurred, so something clever here
    Response.Write "oops, cannot open a connection"
    Response.End
End If
[/CODE]

If you do your connection within a Sub() or Function() block, you should probably exit using Exit Sub or Exit Function, but that's not always true either.

Connection Time-Out

What if the connection is taking a longer time to resolve than usual?  We can handle that too...


[CODE]
On Error Resume Next
conn.ConnectionTimeOut = 15 ' allow 15 seconds to establish the connection
conn.Open dsnString
If err.Number <> 0 Then
    ' an error occurred, so something clever here
    Response.Write "oops, cannot open a connection"
    Response.End
End If
[/CODE]


Recordset Access Failure

Another common issue is when you can successfully open the connection, but cannot read from a table or view because of security permissions.


[CODE]
rs.Open cmd
If err.Number <> 0 Then
    ' do something awesome here
    Response.Write "oops, unable to access the table or view"
    Response.End
End If

If Not(rs.BOF And rs.EOF) Then
cols = rs.Fields.Count
rows = rs.RecordCount
Do Until rs.EOF
' do something neato here
rs.MoveNext
Loop
End If

rs.Close
conn.Close
Set rs = Nothing
Set cmd = Nothing
Set conn = Nothing
[/CODE]


Connection Management

I've seen more situations than I can count where a single page of code (script file, web page, etc.) makes repeated requests from a database in sequential order (as the page is rendered or the script is executed).  Most often it's having to grab data from multiple tables and/or views, or execute multiple stored procedures or functions.  In a lot of cases, the code doing the heavy lifting is being included from separate files (using "includes").  That's all nifty and modular, which is a good approach, but always be VERY careful with that approach that you don't have each module do it's own connection open/close management.  This not only slows down the processing, but it requires more bandwidth and more load on the network and the database server as well.

A case in point might be a web page that renders a report of an employee, then it displays a table with performance evaluation records, followed by a table of employees managed by the employee in question.  If those data repositories are all on different database servers that may be all you can do, but if they happen to be on one server, or even in one database, you should seriously review minimizing the number of open/close requests on your connections.

A brief sample of this using pseudo code:

open connection1
open recordset1
close connection1
open connection2
open recordset2
close connection2
open connection3
open recordset3
close connection3

might work a lot faster and better as...

open connection
open recordset1
open recordset2
open recordset3
close connection

Some people prefer to open a "global" or "session" connection, whereby the connection is opened upon login or initialization by each user session.  The connection object itself is stored in the session stack and made available globally to that user throughout their session window.  Each concurrent user has their own connection opened and maintained on a stack.  Granted this makes it easier to run queries, updates, etc. without the overhead of managing connections at the more granular page/script level, but it definitely taxes the database server with a lot of unnecessary open connections.  For a handful of users that may be fine, but with hundreds or thousands of users it can be a mess and make the database server drag.

Just some random thoughts after beer.  Have any thoughts you'd like to share?
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in applications, asp, databases, scripting, software development, sql server, vbscript, web development | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Voting Time: Help Me Out?
    I need to get a better view of how I should manage this blog if I'm going to keep at it. I'd like to know how you typically discover...
  • A World Without Competition
    Try to imagine what things would be like today had there not been fierce competition in certain key parts of our world.  I’ll give you some ...
  • Book Update
    I posted some gibberish a few weeks ago about another book project.  Well, I'm getting close to wrapping it up, so I thought I'd go ...
  • Cost
    Software technology, like any technology, provides a means to solving problems.  Some big. Some small.  Some that help.  Some that hurt.  An...
  • Windows 7: Default User vs All Users
    A lot of confusion seems to occur with understanding the difference between the "Default User" profile, and the "All Users...
  • Time to Give Props
    With the ever-expanding volume and breadth of information on the Internet today, it's easy to focus on my own thoughts, experiences, ide...
  • Table of Contents (Preliminary)
    Here's the preliminary Table of Contents for my new book "The AutoCAD Network Administrator's Bible - 2013 Edition".  I...
  • The Nicest IT and IT Vendor Folks I Know
    I've ranted many times before how it's unfair to "hate" an entire company, without providing a rationale for it based on s...
  • Windows 8
    Two small, yet irritating things, that I hope Windows 8 addresses with respect to Windows 7: Being able to put the Recycle Bin in the S...
  • Stupid Assumptions
    After years of watching sci-fi TV shows, movies, etc. it's finally come to a point where even the so-called brightest of our authors and...

Categories

  • a
  • activation
  • active directory
  • advertising
  • agile
  • agility
  • amazon
  • american
  • apple
  • application virtualization
  • applications
  • art
  • articles
  • asp
  • augi
  • authors
  • autocad
  • AutoCAD Autodesk
  • autodesk
  • autolisp
  • automation
  • automotive
  • backups
  • batch
  • beer
  • beta
  • blackberry
  • blogs
  • bongloads
  • book
  • books
  • Books writing kindle amazon technology business projects
  • browsers
  • business
  • cad
  • career
  • certification
  • chrome
  • city government
  • civilization
  • cloud services
  • cmd
  • cmmi
  • comedy
  • command
  • community
  • computers
  • conferences
  • config manager
  • consultants
  • consulting
  • contracting
  • cranium drainium
  • crapware
  • culture
  • data center
  • data mining
  • databases
  • deployment
  • directx
  • DLL
  • domains
  • dumb
  • earth
  • economy
  • editor
  • education
  • election
  • elections
  • employment
  • engineering
  • entertainment
  • environment
  • error monitoring
  • events
  • exchange
  • facebook
  • family
  • firefox
  • flexnet
  • fud
  • fun
  • funny
  • games
  • gary vaynerchuk
  • gmail
  • google
  • government
  • group policy
  • hampton roads
  • health
  • history
  • holidays
  • home
  • html5
  • humor
  • hyper-v
  • iis
  • industry
  • infrastructure
  • installation
  • installshield
  • internet
  • internet explorer
  • interviews
  • jobs
  • jtbworld
  • kindle
  • kixtart
  • lab setup
  • languages
  • ldap
  • learning
  • legal
  • licensing
  • life
  • lifecycle
  • linux
  • lisp
  • logging
  • management
  • manufacturing
  • marketing
  • markets
  • mdop
  • mdt
  • medical
  • messaging
  • microsoft
  • microsoft access
  • military
  • mountains
  • movies
  • mozilla
  • music
  • nature
  • network administration
  • news
  • nook
  • nothing
  • office
  • open source
  • openoffice
  • opera
  • operating systems
  • oracle
  • osx
  • packaging
  • patches
  • people
  • photos
  • podcasts
  • policy
  • politics
  • powershell
  • predictions
  • process automation
  • products
  • programming
  • projects
  • psychology
  • publishing
  • rail
  • reading
  • registry
  • religion
  • reporting
  • reviews
  • rsat
  • rss
  • safari
  • safety
  • sales
  • satire
  • sccm
  • scheduling
  • science
  • scripting
  • search
  • security
  • servers
  • services
  • sharepoint
  • shopping
  • sms
  • social stuff
  • society
  • softgrid
  • software assurance
  • software deployment
  • software development
  • software packaging
  • sony
  • speaking
  • sports
  • sql express
  • sql server
  • statistics
  • Statistics news marketing
  • steve jobs
  • stories
  • stuff
  • stupidity
  • symantec
  • sysinternals
  • system center
  • systems architecture
  • t-sql
  • taxes
  • technet
  • technical support
  • technology
  • TED
  • ted talks
  • testing
  • textpad
  • thoughts
  • traffic
  • training
  • transportation
  • travel
  • troubleshooting
  • tutorials
  • twitter
  • ubuntu
  • unattend
  • unemployment
  • updates
  • upfront ezine
  • utilities
  • vacation
  • vba
  • vbscript
  • video
  • virginia
  • virginia beach
  • virtualization
  • visual lisp
  • vmware
  • vmware server
  • voting
  • war
  • weather
  • web
  • web browsers
  • web development
  • web sites
  • windows
  • windows 7
  • windows live
  • windows server
  • windows server 2012
  • windows8
  • winpe
  • wise
  • wmi
  • work
  • writing
  • ws08
  • wsus
  • wwa
  • x64
  • xml
  • ze frank

Blog Archive

  • ►  2013 (37)
    • ►  October (1)
    • ►  September (5)
    • ►  August (8)
    • ►  July (2)
    • ►  June (4)
    • ►  May (4)
    • ►  April (2)
    • ►  March (2)
    • ►  February (8)
    • ►  January (1)
  • ►  2012 (120)
    • ►  December (14)
    • ►  November (12)
    • ►  October (10)
    • ►  September (7)
    • ►  August (3)
    • ►  July (2)
    • ►  June (6)
    • ►  May (6)
    • ►  April (20)
    • ►  March (16)
    • ►  February (18)
    • ►  January (6)
  • ▼  2011 (343)
    • ►  December (15)
    • ▼  November (23)
      • AU Virtual 2011 - Network License Manager Course
      • Panning for Gold
      • Good Enough is NOT Good Enough
      • Google Plus vs Facebook: URL Resolution
      • When They Just Don't Get It
      • Book Update: Corrected Version Coming Soon
      • Stupid Assumptions
      • Guns vs Marijuana
      • It is now available on Amazon.com!Download a free ...
      • Book Announcement: Packager's Pocket Reference, 2n...
      • Computer Accounts vs Service Accounts, Round 3
      • Friday Night Brain Dump
      • Don't Forget the Eggs: ADO basic errors
      • Do as I say...
      • My Favorite Personal Quotes
      • Ticking Down the Days
      • The Identity Illusion
      • Lowest Bidder
      • If This Were a Perfect World...
      • Another Rant
      • My Favorite Drummers and Percussionists
      • Walk and Talk
      • 11 Most Common Mistakes with Error Handling
    • ►  October (27)
    • ►  September (35)
    • ►  August (29)
    • ►  July (17)
    • ►  June (23)
    • ►  May (20)
    • ►  April (38)
    • ►  March (61)
    • ►  February (54)
    • ►  January (1)
Powered by Blogger.

About Me

Unknown
View my complete profile