Click here to Skip to main content
Click here to Skip to main content

Accessing Microsoft Access databases in ASP using ADO

By , 26 Apr 2000
 
  • Download source files - 29 Kb
  • Introduction

    Windows DNA provides a means to provide your user interface, business logic and data sources as separate services working together in harmony over a distributed environment. The browser has become an extremely powerful, yet simple method of providing the user interface, since it handles the network considerations and allows you to create rich user interfaces through simple scripting, HTML and style sheets.

    Your database considerations can be taken care of simply through the use of SQLServer or the Microsoft Jet Engine, and your business logic - the guts of your application that processes the data from the database and sends it to the browser - can be simple ASP pages (enhanced with ActiveX controls if the fancy takes you).

    Once you have the basics of ASP, HTML and VBScript the business logic and user interface are taken care of quickly and simply - but how do you use ASP to access your database and hence complete your 3-tier application? Read on...

    Simple database Access using ADO and ASP

    For this example we'll use Access .mdb databases - but we could just as easily use SQLServer by changing a single line (and of course, configuring the databases correctly). We'll be assuming your application is ASP based running on Microsoft's IIS Webserver.

    We use ADO since it is portable, widespread, and very, very simple.

    The Connection

    To access a database we first need to open a connection to it, which involves creating an ADO Connection object. We then specify the connection string and call the Connection object's Open method.

    To open an Access database our string would look like the following:

    Dim ConnectionString
    ConnectionString = "DRIVER={Microsoft Access Driver (*.mdb)};" &_
                       "DBQ=C:\MyDatabases\database.mdb;DefaultDir=;UID=;PWD=;"

    where the database we are concerned with is located at C:\MyDatabases\database.mdb, and has no username or password requirements. If we wanted to use a different database driver (such as SQLServer) then we simply provide a different connection string.

    To create the ADO Connection object simply Dim a variable and get the server to do the work.

    Dim Connection
    Set Connection = Server.CreateObject("ADODB.Connection")

    Then to open the database we (optionally) set some of the properties of the Connection and call Open

    Connection.ConnectionTimeout = 30
    Connection.CommandTimeout = 80
    Connection.Open ConnectionString
    

    Check for errors and if everything is OK then we are on our way.

    The Records

    Next we probably want to access some records in the database. This is achieved via the ADO RecordSet object. Using this objects Open method we can pass in any SQL string that our database driver supports and receive back a set of records (assuming your are SELECTing records, and not DELETEing).

    ' Create a RecordSet Object
    Dim rs
    set rs = Server.CreateObject("ADODB.RecordSet")
    
    ' Retrieve the records
    rs.Open "SELECT * FROM MyTable", Connection, adOpenForwardOnly, adLockOptimistic
    

    adOpenForwardOnly is defined as 0 and specifies that we only wish to traverse the records from first to last. adLockOptimistic is defined as 3 and allows records to be modified.

    If there were no errors we now have access to all records in the table "MyTable" in our database.

    The final step is doing something with this information. We'll simply list it.

    ' This will list all Column headings in the table
    Dim item
    For each item in rs.Fields
    	Response.Write item.Name & "<br>"
    next
    			
    ' This will list each field in each record
    while not rs.EOF
    		
    	For each item in rs.Fields
    		Response.Write item.Value & "<br>"
    	next
    		
    	rs.MoveNext
    wend
    	
    End Sub
    

    If we know the field names of the records we can access them using rs("field1") where field1 is the name of a field in the table.

    Always remember to close your recordsets and Connections and free any resources associated with them

    rs.Close
    set rs = nothing
    
    Connection.Close
    Set Connection = nothing
    

    Conclusion

    This has been an extremely simple demonstration without serious error checking or even legible formatting of the output, but it's a base to start with.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    Chris Maunder
    Founder CodeProject
    Canada Canada
    Member
    Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
     
    His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
     
    He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
     
    Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

    Sign Up to vote   Poor Excellent
    Add a reason or comment to your vote: x
    Votes of 3 or less require a comment

    Comments and Discussions

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    Questionerror [modified]memberPanzer204 Dec '12 - 4:36 
    sir its showing error on End Sub why??????

    modified 4 Dec '12 - 11:29.

    GeneralMy vote of 3memberMember 427879126 Jan '11 - 17:34 
    fn
    Generalplease be clearmemberdogan_sezgin2 Jun '06 - 5:59 
    when l check the title it says about ms access database but in your code is explanation how to connect to sql database please be carefulyy
     
    asp advanse
    GeneralRe: please be clearmemberNabeel Anwer11 Mar '07 - 23:46 
    test
    QuestionTwo systems with one database!memberPetrax24 May '06 - 23:00 
    how would it works the online reservation and billing system with one database, just because the billing is an offline system. Is there a way or solution for this problem????Confused | :confused:
    GeneralWorked! first time!! How do I arrange the datamemberSkippy_melb27 Feb '06 - 18:34 
    I am so pleased. After struggling for weeks on getting a simple database to work, this simple script just... did it!!!
     
    Now I'm getting excited. I have about 40 fields in my database and they spread right across to the right.
    How do I 'arrange' the tables so the data all shows on one page and i can
    a. Print it.
    b. Delete a record
    Hope I'm asking for too much.
     
    Thanks again. (Can you tell I'm happy??)
     
    A happy skippy
    QuestionError??sussAnonymous26 Oct '05 - 13:04 
    Error Type:
    ADODB.Recordset (0x800A0BB9)
    Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.

    QuestionPlease give me a way for display pictures which store in DB Access 2003 by &quot;OLE object&quot;?membertuyenhnp25 Sep '05 - 16:47 

     
    Hi all!
    I store my picture in Access 2003 by "OLE Object".
    I am coding a ASP page for loading and display those pictures. But I am not know any way which display those pictures in my ASP page.
    Please, give me a way. Thanks very much.
    Questionhow can i access Oracle DBMS using aspsussAli Idrees Bhuttah21 Sep '05 - 19:20 
    hi dears
    I want to access Oracle Database from ASP. I'm new. Can anyone guide me. I'll be thankful. Thanx in advance for +ve quick respose.
     

     
    Watch Your Thoughts for they will become your actions.
    Watch Your Actions for they will become your habits.
    Watch Your Habits for they will become your beliefs.
    Watch Your Beliefs for they will determine your destiny.
    GeneralAccess TutorialsmemberBatchwood13 Jul '05 - 7:51 
    Here is a link to a number of Access articles & tutorials that may be of help to someone:
    http://www.findingfacts.com/L3/L3_54_56_57.php
     
    Hope it helps
    Regards
    GeneralUsing Ms-Access in .netsusseyalgr120 Nov '04 - 3:28 
    Hi
     
    I would like to insert 900000 records to Ms-Access database using .net .
    The problem is that it takes something like 15 minutes to do so.
    I tried to use DAO 3.6 in vb6 and it took 4 seconds for 70000 records.
    I would like to know: Is there is a better .net tool to insert the records? if not, How can i use Dao 3.6 in .net envirament?
    (the OpenDatabase and OpenRecordset methods demand all the parameters, not as in vb6 and i don't know which parameters to supply to those methods).
    Thanks,
     
    Eyal
    QuestionHow I detect connection to MS Access file error?memberATC7 Sep '04 - 10:42 
    Hi,
     
    I use the folloring to connect to my MS Access database:
    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Open "\database\Myfile.mdb"

    What happen if the Myfile.mdb is corrupted or missing ... how can I detect it (where is the error returned)? To prevent my page.asp show to the brownser "the error" then hang up!
    Many thanks,

    Generalurgentmemberpavancode21 Jul '04 - 22:31 
    how to update table row in access.
    requirement is: it is a E_commerce project, whenever user selects a products it should be enter in to a temp table if order confirm it will generated the money trensation else it will deleted from the temp table, But how to make updation when user selects same products, qty must be change according to thew product id,
     

    Temp table fields are:--- seesionid, tproductid,tqttyConfused | :confused:
    Generalcan't access databasememberJDG3 Mar '03 - 20:20 
    Hi
     
    I can't access the database. Is the ../demo.mdb and Table1 the correct inputs?
     
    tx
    GeneralRe: can't access databasememberverma_aditya22 Feb '04 - 22:18 
    Poke tongue | ;-P Rose | [Rose] D'Oh! | :doh: Sigh | :sigh: Eek! | :eek: Cool | :cool: D'Oh! | :doh: Cool | :cool: Frown | :( img src="/script/Forums/Images/smiley_cry.gif" align="top" alt="Cry | :((" /> Blush | :O OMG | :OMG: WTF | :WTF: Roll eyes | :rolleyes: Mad | :mad: Hmmm | :| Eek! | :eek:
    GeneralRe: can't access databasemembersanjaygarg18 Aug '04 - 1:14 
    Correct Inputs are
    demo
    table1
     
    demo
    table2
    GeneralRecord set is emptymembermsokol3 Dec '02 - 4:37 
    Using the sample code in this posting.. my app returns empty results table.
    Using NT4 (SP5) workstation.. I have Office 2000 MS Access and I notice that there is C:/Program Files/Common Files/System/ADO folder so there include files for ADOVBS are available.The HTM file with the ASP ADO references and the data base are all on the same workstation. Not connecting over a network yet. Am I missing something else?
    GeneralAccess db convertion failsussAnonymous11 Jul '02 - 18:30 
    Hi,
    I've access 97 db, and tried to make connection from Dreamweaver MX. The connection was ok when I tested, but there is no fields in tables. Well figured out that Access97 is not supported, I converted my db to access 2000, still, there is no fields in the tables (the connection is OK).
    Can someone tell me what is wrong and how to solve the problem?

    GeneralView Jpg/ Gif stored in my databasemember2IT6 May '02 - 10:31 
    I created a database with text and images I can see
    text but when I try with the same script( obviously
    adding Response.BinaryWrite objRS("Picture"))
    I can't see anything when I cancel Response.BinaryWrite objRS("Picture")
    I see binary text !!!!
     
    Can someone help
    Thanks a lot
     

    Dead | X|
    GeneralRe: View Jpg/ Gif stored in my databasesussAnonymous4 Aug '02 - 16:37 
    Itis very simple, just following this way:
    what you save in your database is just path of the image to the folder you store your images. you intend to display
    to display it, just do this : <img=<%=rs("pathpicture")%>>
    of course to do this you need to create a recordset which hold picturepath. wish you succeed

    GeneralRemote Data Service,help!memberJz17 Mar '02 - 7:22 
    Anyone know how to set up connection with a different web server or ftp server from a web server. How to set the connectionString or something else? Thanks.
    QuestionHow to Connect from ASP to MS-Access(Database)memberMann3 Dec '01 - 17:31 
    Hi,
     
    I tried in all combinations,
    what the code given by the MSDN, Sams in 21 days,
    But still it is not connecting to the Database(Ms-Access).
     
    What is the correct procedure....?
     

    Thks,
    Mani.;P
     
    Mann.
    GeneralAccess Macrosmemberhhayes18 Sep '01 - 3:41 
    I know how to use query's in access as stored procedures and call them from ASP, but I need to be able to call a macro from my page. Can this be done?
    GeneralRe: Access MacrosmemberMatt Gullett6 May '02 - 11:10 
    no.
     
    Access only exposes support for queries and tables. Macros and modules are not accesible. Even worse, queries which use custom functions will fail.

    GeneralIIS application in Visual Basic 6.0memberSelcuk Yazar5 Sep '01 - 6:57 
    Hi I want to retrieve data using ADO in my IIS application. Records retrieve correctly
    bu my template .html file don't them show correctly why?
    GeneralSingle QoutesmemberHugo13 Jul '01 - 1:26 
    When i try to use 'single qoutes' in the insert, update within a form the server returns an error because the string is already inside a single qoute
     
    how can i insert, update and performe a single quote query???
     

    Eek! | :eek:
     
    HammerHeadPT
    GeneralRe: Single Qoutesmemberbluesky8 Nov '01 - 14:07 
    hi
    you have to double quote it:
     
    'insert values(''Mother'', 1, ''Australia'')'
     
    hth
    bluesky
    GeneralOLE Through LinuxmemberAlex K.13 Apr '01 - 18:25 
    I have Halcyon iASP and MySQL installed on my server. I was wondering how i could Access a MS.Jet.OLE database through ASP on the Linux Machine..
     
    I've checked everywhere, but no site had any info on that. Seems that all ASP sites are IIS/PWS based
    GeneralRe: OLE Through Linuxsusssvante_ahmad8 Sep '02 - 23:08 
    I have same problem with you.
    I think you must create a gateway in windows (place where MS Access database exists).this gateway could be connected by application that developed in Linux and will connect to mysql server.
     
    regards
    Baqir

    QuestionAccessing MS Access through a firewall using ASP?memberAnonymous24 Jan '01 - 3:47 
    How do you access an Access database through a firewall?
    AnswerRe: Accessing MS Access through a firewall using ASP?memberAnonymous21 Jul '01 - 15:17 
    Set the firewall perimeters to enable MSQLACC + version;)
     
    Johnty
    GeneralADO and ASP/IISsussDennis16 Aug '00 - 3:06 
    This is probably an elementary question but, ...
     
    I cannot have the database open with Access and still open it with code like you are using. Am I missing something?
     
    I can share the database otherwise, but not with IIS/ASP?
     
    Sorry if this is too simple a question
     
    Thanks in advance
    GeneralRe: ADO and ASP/IISmemberblueksky8 Nov '01 - 14:11 
    howdy
     
    I asume that you would like to work on the db and share it at the same time with users via your Intranet/Internet?
     
    If this is the case you could split up the database in a mdb where you've got only the data and another mdb where you have only the GUI. You then can link the tables and views into the GUI mdb and work as before.
     
    The ASP Application must then access the data mdb.
     
    hth
     
    bluesky
    GeneralSQL Search syntaxsussDavid Gallagher15 Jun '00 - 11:49 
    Nice simple article which gave me the knowledge to create a simple query system over my intranet.
    I used Access to generate my SQL, and I found that when I searched for '*' ADO returned no records. Acces did.
    After much searching I realised that ADO uses ANSI SQL and needs a WHERE clause of '%' for a wildcard search.
    Hope this saves you the time it took me to find this out!

    GeneralRe: SQL Search syntaxsussSaul Toohey24 Apr '03 - 5:36 
    Thank you so very much for this tid bit of information. I have searched long and hard for this answer and you made my day. It works like a charm of course.

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Permalink | Advertise | Privacy | Mobile
    Web04 | 2.6.130516.1 | Last Updated 27 Apr 2000
    Article Copyright 2000 by Chris Maunder
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid