Important alert: (current site time 7/15/2013 10:00:39 PM EDT)
 

article

Database Connectivity and Data Access

Email
Submitted on: 1/10/2001 3:16:33 PM
By: Daniel M. Hendricks  
Level: Beginner
User Rating: By 20 Users
Compatibility: ASP (Active Server Pages)
Views: 190964
author picture
(About the author)
 
     This article shows various connection strings, used to connect to various databases in Windows, as well as methods to access and modify data. Some connection strings may require client software to be installed, but most work with Windows 2000.

 
 
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.
				Database Connectivity in ASP

This reference will show you how to connect to a variety of databases in different ways:

  1. Connect to the Database
  2. Run your SQL commands
  3. Common Examples

Connect to the Database

Before you can access your database, you need to connect to it using one of the following methods:

Microsoft Access 2000 Database (OLE-DB):

Set db = Server.CreateObject("ADODB.Connection")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("database.mdb") & ";"

Microsoft Access databases are quick, easy, and portable. It works good for small, intradepartmental applications. If you plan on having more than a few users connecting to it, however, you many wish to consider using a database like SQL Server or Oracle instead. Here is another way to connect to a Microsoft Access database:

Microsoft Access 2000 Database:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("database.mdb") & ";UID=;PWD="

For a description of the difference between OLE-DB and ODBC, check out this article at oledb.com.

Connecting to a database using a DSN:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "DSN=mydsn;UID=username;PWD=password"

Before you can use this method, you must create a DSN in your control panel (usually under ODBC or Data Sources). This process varies from each version of Windows, so you're on your own. When you create a DSN, you will be asked to give it a name. The name you enter should replace the "mydsn" value above, along with the username and password.

Connect to a SQL Server database with OLE DB:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "Provider=SQLOLEDB; Data Source=SERVER; Initial Catalog=database; User ID=username; Password=password"

An OLE DB connection can provide faster performance than a DSN. This method doesn't require you to set up a DSN (which makes reloading the machine easier), which makes it easier to reload the computer and doesn't require you to create a DSN. However, if you move your applications to another server or if you move your database to another server, you will need to update any hard-coded values. There are ways around this, but for simplicity, I have provided the example above.

Connect to a MySQL Database Under Linux/Chili!Soft ASP:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "Driver={MySQL}; SERVER=localhost; DATABASE=database; UID=username; PWD=password"

This code has only been tested on a Cobalt RAQ with Chili!Soft ASP and MySQL.

Connect to Oracle 8 (OLE-DB):

Set db = Server.CreateObject("ADODB.Connection")
db.Open "Provider=OraOLEDB.Oracle;User ID=user;Password=pwd; Data Source=hoststring;"

This code has only been confirmed to work with Oracle 8i server and Windows client. Important: Requires Oracle client connectivity tools to be installed. Here is another way to connect to an Oracle database:

Connect to Oracle 8:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "Driver={Microsoft ODBC for Oracle};UID=user;PWD=password;CONNECTSTRING=hoststring"

This also requires the Oracle client tools be installed. For a description of the difference between OLE-DB and ODBC, check out this article at oledb.com.


Run Your Commands

Now that you have a connection to your database, you can run SQL statements:

Delete Records:

db.execute("DELETE FROM mytable WHERE FullName = 'John Doe'")

This is only used as an example. You will need to replace "mytable" with the name of the table you are trying to delete from. Likewise, replace "FullName" with the name of the appropriate field.

Insert Records:

db.execute("INSERT INTO mytable VALUES ('John Doe', 22, '321 Disk Dr.', 'Hollywood, CA')

Again, this is only used as an example. Change the statement as needed.

List Records:

set rs=db.execute("SELECT * FROM mytable")
rs.MoveFirst
Do Until rs.EOF
Response.Write rs("MyField") & "<br>"
Loop

The first line is a select statement that selects records. The following lines iterate through each line, displays the current value of the "MyField" field, and adds a line-feed. You will want to change the "mytable" and "MyField" values appropriately.


Common Examples

Add, list, and delete records:



Set db = Server.CreateObject("ADODB.Connection")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("database.mdb") & ";"

db.execute("INSERT INTO MyTable VALUES ('Dan Hendricks', 22)")
set rs=db.execute("SELECT * FROM MyTable")

rs.MoveFirst
Do Until rs.EOF
Response.Write rs("NAME") & "<br>"
rs.MoveNext
Loop

db.execute("DELETE FROM MyTable WHERE NAME = 'Dan Hendricks'")

This code will open the database, add the values "Dan Hendricks" and "22" into the first two field of the chosen table, display all current records in the table, and finally delete the record that was added.

Here is another quick and easy way to connect and list records:

'This code connects to the database.
set rs=Server.CreateObject("ADODB.Recordset")
db="DSN=TechSupport;UID=TechSupport;PWD=foobar"

'This code iterates through the current records.
mySQL = "SELECT * from chairs "
rs.open mySQL, db, 1, 3<-- Change the '3' to a '1' for a read-only. -->
rs.MoveFirst
Do Until rs.EOF
Response.Write rs("MyField") & "<br>"
rs.MoveNext
Loop

'This code deletes a record, and then adds a new one
rs.MoveFirst
rs.Delete
rs.AddNew
rs("Name") = 'Jane Doe'
rs.Update
rs.Close

NOTE: This does not use the same connect statements listed above. It's just a different way to connect to a database and list, add, or remove records.


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner 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

1/11/2001 12:38:34 PMRobert Long

Great tutorial, I really appreciate you going into detail with every point. I'll be looking forward to other articles in the future. Any IIS applications?
(If this comment was disrespectful, please report it.)

 
1/11/2001 2:07:28 PMJohn A. Shaw

Dan,

In your contribution on Database Connectivity you state that:

**********
There are a number of ways to
connect to a MS Access database, but I use this one.

Connecting to a database using a DSN:

Set db = Server.CreateObject("ADODB.Connection")
db.Open "DSN=mydsn;UID=username;PWD=password"
**********

1) Do you know of a source for the other ways? For accessing other MS Office applications?

2) I want to open an Excel Workbook and execute a VBA macro from an ASP. Do you have any suggestions where I might find information on this task?

Thanks for your piece on Database Connectivity and any help you may be able to give me.

.............John
(If this comment was disrespectful, please report it.)

 
1/23/2001 12:36:21 AMtanuj: email: tanujwadhwa@hotmail.com

Tell me which one of these is better
(If this comment was disrespectful, please report it.)

 
3/1/2001 11:13:47 PMDan Hendricks

Neither method is better. Each one is sometimes convenient for different code. The second one is more straight-forward and easier to understand. I like to use it for displaying records in a table. I like to use the first one for most stuff because it more clearly displays what is going on through SQL statements. Neither is better - use what you like!
(If this comment was disrespectful, please report it.)

 
6/16/2001 4:46:51 PMHarlan Iverson

Hey, awesome, thanks...This was the only thing on the net, after 2 days of searching, I found that acually told me how to connect to my MySQL server. The Chili Soft ASP method also works with IIS 5.0 thanks
(If this comment was disrespectful, please report it.)

 
6/16/2001 4:47:58 PMHarlan Iverson

oh, one last thing i forgot to mention, incase anyone else is having the same problem i was, you need MyODBC installed too, can get it from the MySQL website.
(If this comment was disrespectful, please report it.)

 
6/29/2001 3:14:01 PMMIGUEL A SANTIAGO

What does it is command to APPEND TO an external Access database with password.
Access automatically create next command:
INSERT INTO [;PWD=xx].TblName ( FieldName ) IN 'loc&databaseName'[;PWD=xx]
SELECT SourceTblName.FieldName
FROM SourceTblName;
But doesn't work, it is correct ?
What does is it correct command?
Thank You for you help...

Miguel
(If this comment was disrespectful, please report it.)

 
7/30/2001 2:17:06 PMvolcano_88101

Thank you so much for making it so simple. After Viewing over 200 Web Search Results I was about to give up.. Not only was your code nice and easy to understand but somehow it finally got to me why my website wasn't working. I didn't have an ODBC driver installed.. Thank you so much

(If this comment was disrespectful, please report it.)

 
8/27/2001 2:45:58 PMDaniel Malo

Dan, you did an awesome work here! I tried Access, and it worked smoothly with ASP. But right now, I'm doing a project that involves Oracle 8 with ASP. I followed your suggestions, but I couldn't establish a connection. You see, I have this server with all the necessary drivers and service pack installed (Windows NT Server4.0, Service Pack 6, drivers for ODBC/Oracle). This error appears: "ADODB.Connection error '800a0e7a'. ADO could not find the specified provider."

If you have any suggestions, they are welcome!

Thanks a lot, Dan
(If this comment was disrespectful, please report it.)

 
9/14/2001 10:06:58 PMTodd

This Helped Alot Thanks Man
(If this comment was disrespectful, please report it.)

 
11/6/2001 12:32:51 AMkik333

hi, i am having a totally different problem kinda. My personal web manager stops displaying my asp pages sometimes, and then when i try to run the pws, nothing happens. so i try to uninstall it, but win2k doesn't let me. so now i am stuck with no web server. any one know why this might be happening or if there are any fixes.

(If this comment was disrespectful, please report it.)

 
2/24/2002 3:33:37 AMSoheil Yasrebi

great toturial thanks!
(If this comment was disrespectful, please report it.)

 
4/30/2002 5:30:42 PMArthur Robinson

Is there a way to have the new SubjectID from the first table feed automatically into the other 3 tables?
(If this comment was disrespectful, please report it.)

 
8/30/2002 5:49:33 PMamenelaus

All the information on how to connect to your database is in the IIS help files.

You say this can be used to modify data in the description, yet I see no way to overwrite current records by id. Any help?
(If this comment was disrespectful, please report it.)

 
9/5/2002 3:50:54 AM

This is a great Article and helped me a lot in my project. Thank you very much.
(If this comment was disrespectful, please report it.)

 
10/16/2002 4:33:59 PM

This is a very useful article that can be taken as a reference, good work man
(If this comment was disrespectful, please report it.)

 
12/10/2002 4:07:31 PM

Nice job, thanks. I could be nicer if you add an some code which shows how you can open 2 databases (msAccess) at the same time?
(If this comment was disrespectful, please report it.)

 
7/28/2003 9:56:29 PM

Thanks for this great article, good work Daniel
(If this comment was disrespectful, please report it.)

 
8/20/2003 2:31:45 PM

urgently!!!!!!!!!!! the problem is when i use one of the provided way which is connect the Access 2000. the error occured said that: the server has not object matched!!! what is this mean?!?! how can i slove it?!?!?
HELP!!!!!!!!!!!!!!!
(If this comment was disrespectful, please report it.)

 
9/1/2003 1:55:43 AM

A really clear and easy guide to what I have been having problems doing!

Many thanks
(If this comment was disrespectful, please report it.)

 
2/11/2004 1:45:34 AM

I am tryi
(If this comment was disrespectful, please report it.)

 
3/1/2004 9:10:25 AM

In the list records example rs.MoveNext is missing. Otherwise excelent guide - I am newbie to VBScript and this helped me jumpstart a lot.
(If this comment was disrespectful, please report it.)

 
3/12/2004 10:37:14 AM

I'm trying to update or change a column in my table in an MS-Access database, and I'm gettin an error:

ErrorType:
Microsoft JET Database Engine (0x80004005)
The Operation have to use a query that can be updated.

' Förbered SQL-fråga
Dim strSQL
strSQL =
(If this comment was disrespectful, please report it.)

 
5/14/2004 6:42:46 AM

I am getting this error message when connecting Oracle using ASP.
OraOLEDB (0x80004005)
ora-12514: TNS:listener could not resolve SERVICES_Name given
in connection descriptor

I am working on uni server

here is the connection string
db.Open "Provider=OraOLEDB.Oracle;User ID=user;Password=scott; Data Source=127.0.0.1;"


Looking for ur response
safdar satti
(If this comment was disrespectful, please report it.)

 
8/2/2006 6:27:45 AMhellow

goid conneid
(If this comment was disrespectful, please report it.)

 
11/21/2007 2:59:18 AMmahmoud

good
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.