ASP,will,introduce,less,known,technique,acces
Quick Search for:  in language:    
ASP,will,introduce,less,known,technique,acces
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
ASP/ VbScript Stats

 Code: 132,008 lines
 Jobs: 161 postings

 
Sponsored by:

 

You are in:

 
Login


 

 


Latest Code Ticker for ASP/ VbScript.
List Records
By Edito P. Aspra Jr. on 8/26


DSN Less Connection to SQL Server Database
By alpesh shah on 8/26


Click here to see a screenshot of this code!Database Driven Select Menu w/ default select
By Jayson Starkey on 8/26

(Screen Shot)

A Simple guestbook in ASP
By Matthew Meadows on 8/25


Simple GuestBook or Feedback Page Requiring No Database Implementation
By Ken Alabi on 8/25


if i remember, this is a M. Harris code sample
By ask on 8/24


MTS Registration Script
By Igor Krupitsky on 8/23


Click here to see a screenshot of this code!Creating Windows Users with ASP and ADSI
By jamespwalters on 8/23

(Screen Shot)

News Poster (Advanced)
By Martin Kilbryde on 8/22


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

ASP Tip: Simplify Your Database Query

Print
Email
 

Submitted on: 11/13/2001 4:41:36 AM
By: Hendry Cahyadi 
Level: Intermediate
User Rating: By 7 Users
Compatibility:ASP (Active Server Pages)

Users have accessed this article 12508 times.
 
(About the author)
 
     I will introduce you a less known technique to access a database using ASP. Really simplified your development and saves your time much! Just Read on...

This article has accompanying files
 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

Writing Query for accessing information in a database is one of the most frequently tasks that ASP programmers do. In here, I will introduce you a less known technique by ASP programmers that's called Parameterized Query. But, Firstly let's we recap our old habit when doing query to a database.

Do you Remember that there's a rule of thumb when building your query? You have to use query mark as a sign for your data. For example take a look at the snippet code below. This is a simple string query that's define select query to an Employees table in a Northwind database: (Note that I don't write the data access code, I assume most of you know it)

<%
...
sEmpId = 1
sHireDate = "1 January 1993"
sCountry = "USA"
strSql = "SELECT FirstName, LastName, Title FROM Employees WHERE ((EmployeeID >"  & sEmpId & " AND HireDate >#" & sHireDate & #) AND Country = '" & sCountry & "')"
...
%>

In the above query I define a string query in a variable, named strSql. This time I want to build dynamic sql query, i.e. I embedded some variables whose values may come from user input (already put in the sEmpId, sHireDate, and sCountry variables). Notice that for variable which is a string type (sCountry), I have to enclose it with an apostrophe sign (') and for date-time variable type (sHireDate), I have to enclose it with a pound sign (#) and for numeric type variable (sEmpId) you have no special mark sign for it. If you hardcoded the value into your string query, you still have to follow these rules. As I said before that this is a rule of thumb, so you have to follow it or your query won't work at all!

 So What's wrong with this? First, you have to remember all the signs for the appropriate data type and you have to put it rightly (enclosed it in a well-formed manner, also be careful of spaces between the sign and query keywords). Next, the other bad thing is these sign markers are different for each database! If you rewrite that query for MS SQL Server database then the query mark sign for date-time type variable is not a pound sign (#) but an aposthrope (') So not only you have to remember diffent sign for different data type, you also have to remember the signs for different database type. Not just that ... the worst beast here is when you have to build a complex query, that's made up over ten lines or even hundred of lines, then you will have difficulty to read such a query which mixed up with all those signs. Also you tend to have trouble when you want to fix it. And the last thing, since we use many special signs so you must always remember to escape your data from query mark signs. For instance, if one of your data contains an aposthrope (') within it, you have to escape it and most ASP Programmers do like this one:

sCountry = "USA'" 'Notice at an aposthrope at the end - this is not allowed...
sCountry = Replace(sCountry,"'","''") 'So Escape it by Replacing all single aposthrope with double aposthrope

Now, Comes Parameterized Query. To get rid of all those trouble maker, we can utilize ADO Parameterized Query feature. It's very easy and can also make your life easier. The parameterized query is simply just a query that's embedded with one or more parameters and the sign for each parameter is a question mark (?). Later, we will associate all the parameters with the actual value we needed. Below is the demonstration of parameterized query (available for download)  and I still use the above query. This time, I write it in full code and add a little stuff. I demonstrate how to use a select query and an updateable query type. Note that if you can't read the code in html version below, please download the accompanying file (full documented), you will be more comfortable to read it using your favorite editor.

<%

Option Explicit

Dim oCmd, oRs, sSQL, sEmpId, sHireDate, sCountry, sCompName, sPhone, iShipperId
Dim sCnnString, sDBPath, iRec

'This is a simple script that demonstrat ' es the harness and easiness of parameter ' ized query
'The First one demonstrates select query ' operation
'The Last demonstrates update query oper ' ation

'Define connection string, the database ' file is located at the same directory wi ' th the script
'The database file is NWind.mdb (MS Acce ' ss type, available if you install Visual Studio):
sDBPath = Server.MapPath("NWind.mdb")
sCnnString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" & sDBPath

'Populate a Command Object

set oCmd = server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = sCnnString

'Demo1: Select Query Operation
'Define Input values
'For simplicity sake, I hardcoded these ' values.

sEmpId = 1
sHireDate = "1 January 1993"
sCountry = "USA"

'Define Our Query in a variable (sSQL)
'Notice that we get rid of query signs s ' uch as quote (') or pound (#)
'We just use question mark (?) as the pl ' aceholder for all the input values, no m ' atter what the type it is.
sSQL = "SELECT FirstName, LastName, Title FROM Employees " & _
       " WHERE (EmployeeID > ? AND HireDate > ? AND Country = ?)" < BR >
'Put our query in the command object and Invoke Execute method to get the recordset
'We Associate the query parameter with t ' he real values in the array function.
'If you wish you can use a safe array ty ' pe variable instead of array function
'Remember that put your values in the sa ' me order as you defined the parameter(?) ' in your query.
'Notice that in here we call Execute met ' hod with parentheses (as function) since ' we will get the return value,ie the reco ' rdset object
oCmd.CommandText = sSQL
set oRs = oCmd.Execute (,Array(sEmpId,sHireDate,sCountry))

'Display a header

Response.Write ("<H3>Query Results:</H3>")

'Loop over the recordset and print out each value
do while not oRs.EOF
   Response.Write oRs(0) & " " & oRs(1) & " - " & oRs(2) & "<BR>"
   oRs.MoveNext
loop

'Clean up Recordset Object oRs.Close
set oRs = nothing

'Demo2: Update Query operation 'Define input values

sCompName = "Max's Express" 'Notice at the single aposthrope - we don't have to escape it!
sPhone = "(503)505-1001"
iShipperId = 2

'This is just a dummy update operation

sSQL = "UPDATE Shippers SET CompanyName =?, Phone = ? WHERE ShipperId > ?"

'Put the query into command object
'Invoke Execute method to run the query< ' BR> 'We pass a variable that will hold the n ' umber of successful operation and an arr ' ay function to associate our parameter w ' ith real values
'Notice that since we just run update ty ' pe query(no return values) so we don't u ' se parentheses.
oCmd.CommandText = sSQL
oCmd.Execute iRec,Array(sCompName,sPhone,iShipperId)

'Display Message indicated the number of sucessful update operations

Response.Write ("<H4>" & CStr(iRec) & " Records Successfully Updated</H4>")

'Clean up Command Object
set oCmd = nothing

'Last thing to ponder:
'If you change the database to other typ ' es which supports parameterized query, such as SQL Server, ..you don't have to change any of your query and code!

%>

Well..., Easy isn't it? You don't have to remember many signs for different data types, all you have to do is just remembering a question mark sign (?) and this sign is consistent regardless what database type you use. You also don't have to do escape for mark signs. Your query is also more readable and maintainable, even if your query lines are more than ten lines, it's still easier and make sense to read it.

So..Ready to make your life a bit easier? Parameterized your Query!

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzipto decompress it.

Virus note:All files are scanned once-a-day by Planet Source Code for viruses,but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:
1)Re-scan downloaded files using your personal virus checker before using it.
2)NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 3 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
11/18/2001 5:41:23 PM:Mark Focas
This code does not work using SQL Server 7 or Access2000 on windows 2000. It comes up with the following error: No value given for one or more required parameters
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/28/2001 1:04:57 AM:Hendry Cahyadi
Ooops I'm too late.. Mark Focas, I tested my script on Win2000 Professional and my script works well to either SQL Server 7 or Access2000/XP The error message that you got usually comes up when you forget to associate the value to the parameter or you define the number of parameters more than the number of the actual values. Please let me know if you need such more help, I would please to help you.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/29/2002 9:20:25 AM:Tom Roberts
Demo1 works great, however I can not get demo2 working. I get an ASP error when executing the line oCmd.Execute iRec,Array(sCompName,sPhone,iShipperId). Here is the error I am getting: Error Type: Microsoft JET Database Engine (0x80004005) Operation must use an updateable query. Any idea's on how to fix this would be greatly appretiated. Thanks
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/17/2002 3:55:48 AM:Alain Chang
The ADODB.command method seems to limit strings to less than 255 chars. So it doesn't work well to fill memo type entries. Too bad. How else can you escape double quotes in an entry larger than 255 chars? Thanks, Newbie1
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | ASP/ VbScript Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.