Executing All or None queries : ASP Transactions
Saturday, August 15, 2009Introduction
In this article we will learn on how to use database transactions in ASP. This will allow us to execute all database queries or none at all. How many times have you wanted to insert, update a lot of records collectively wanting that either all of them get executed or if there is an error then none is executed at all ? Well, if you haven't this need yet, you will have it in near future.
What are transactions ?"A transaction is an atomic unit of work that either fails or succeeds as a whole." In a transaction there can be any number of things to do, like update one thing, send email, do that thing and so on. If transaction is successful, all of these things will be done or executed as the case may be, or if transaction fails then none of them will be executed.
When a transaction is successful it is said that this transaction has committed and all the tasks that it had to do will be done. If there is some error then the whole transaction will be brought back to it's original state and none of the task that it had to do will be completed, it is called rolling back of the transaction.
Transactions are very simple as you might have learned by now. They are a means to allow us to do many tasks or not to do any of them. There is no such thing in a transaction that one task is done and other is not. Transactions are always executed as a 'whole'.
In this article we will learn a part of these transactions, database transactions. Where we will be able to execute all of the SQL queries or if some error occurs then rollback all the actions and no query gets executed. We will also build a very useful Function to track database errors and show them to the user if some error occurs. We will use this Function to see if there have been any errors in executing any query, if not then commit the transaction otherwise rollback!
Our Access DatabaseCreate a new Access database and save it as db.mdb. Now create a new table in 'design view' as follows :
Save this table as TestTable. After that populate this table as follows :
ErrorsFound FunctionWe will now look at the ErrorsFound ASP Function that will track database errors and report it to the user. You don't need to create a new ASP page now, we will do that on the next page. For now just have a look at this Function and see how easy it is to track database errors.
Function ErrorsFound(mycon) Dim myError
If mycon.State <> 1 Then eStr = "
| Error | Database not found. |
| Page | " & Request.ServerVariables("SCRIPT_NAME") & _ " |
| Date & Time | " & FormatDateTime(Date, 1) & _ " " & Time & " |
"
ErrorsFound = True
ElseIf mycon.Errors.Count > 0 Then For Each myError in mycon.Errors
If myError.Number <> 0 Then eStr = "
| Error Property | Contents | " & _ "
| Number | " & myError.Number & _ " |
| Native Error | " & _ myError.NativeError & " |
| SQLState | " & myError.SQLState & _ " |
| Source | " & _ myError.Source & " |
| Description | " & _ myError.Description & " |
| Page | " & _ Request.ServerVariables("SCRIPT_NAME") & _ " |
| Date & Time | " & FormatDateTime(Date, 1) & _ " " & Time & _ " |
"
ErrorsFound = True End If Next Else ErrorsFound = False End If
End FunctionThis Function will return True if an error is found and False if none. Note this Function can also detect the error if you remove or rename the database.
ExplanationI will only explain the important parts of the Function above.
If mycon.State <> 1 ThenConnection.State property tells us that whether the connection to the database is open or not. If connection is open then it is equal to 1 and if closed then it is equal to 0. So in the above line we check this property to detect if database could be opened or not, if not then we show appropriate error message and exit the Function.
ElseIf mycon.Errors.Count > 0 Then For Each myError in mycon.Errors If myError.Number <> 0 ThenNext we check to see if Connection.Errors.Count is greater than 0 or not. Note that if any errors occur then this error count will be greater than 0. So if there is a non-zero error count then iterate through the Connection.Errors collection and show all the information we have about the error.
'trans.asp' ASP pageCreate a new ASP page and save it as trans.asp in the same directory where you kept the db.mdb database. Copy the following code into and save it again :
| Error | Database not found. |
| Page | " & Request.ServerVariables("SCRIPT_NAME") & _ " |
| Date & Time | " & _ FormatDateTime(Date, 1) & " " & Time & _ " |
" ErrorsFound = True ElseIf mycon.Errors.Count > 0 Then For Each myError in mycon.Errors If myError.Number <> 0 Then eStr = "
| Error Property | Contents | " & _ "
| Number | " & myError.Number & _ " |
| Native Error | " & _ myError.NativeError & " |
| SQLState | " & myError.SQLState & _ " |
| Source | " & _ myError.Source & " |
| Description | " & _ myError.Description & " |
| Page | " & Request.ServerVariables("SCRIPT_NAME") & _ " |
| Date & Time | " & _ FormatDateTime(Date, 1) & " " & Time & _ " |
" ErrorsFound = True End If Next Else ErrorsFound = False End If End Function %><% Dim con Set con = Server.CreateObject("ADODB.Connection") con.Open connStr Response.Write "Opening Connection...
" con.BeginTrans Response.Write "BeginTrans Called...
" con.Execute("insert into TestTable(name) values ('Salim Elahi')") Response.Write "Trying to insert records .no1...
" con.Execute("insert into TestTable(name) values ('Arshad Khan')") Response.Write "Trying to insert records .no2...
" If ErrorsFound(con) = False Then con.CommitTrans Response.Write "Committing Transaction...
" Response.Write "Records added successfully...
" Else con.RollbackTrans Response.Write "Rolling back transaction...
" Response.Write "Records were not added...
" End If con.Close Response.Write "Closing Connection...
" Set con = Nothing Response.Write "Setting Con = Nothing...
" If Len(eStr) Then Response.Write eStr End If ' ADO Constants Const adCmdText = &H0001 Const adCmdTableDirect = &H0200 ' Recordset Object Dim rs, query query = "TestTable" Set rs = Server.CreateObject("ADODB.Recordset") rs.Open query, connStr, , , adCmdTableDirect If Not rs.EOF Then ' Creating the table Dim i, j Response.Write "
| " & Item.Name & " | " Next Response.Write "||
| " ElseIf ds(j, i) = True Then Response.Write " | green;font-weight:bold;"">" Else Response.Write " | " End If Response.Write ds(j, i) Response.Write " | " Next Response.Write "
ExplanationAlthough the code that I provided in the last page looks a lot, but if you take a closer look it is very simple and most of the things you will already be able to understand. con.BeginTrans
Response.Write "BeginTrans Called...
"
After opening the connection to the database, we execute the Connection.BeginTrans method to start the transaction.con.Execute("insert into TestTable(name) values ('Salim Elahi')")
Response.Write "Trying to insert records .no1...
"
con.Execute("insert into TestTable(name) values ('Arshad Khan')")
Response.Write "Trying to insert records .no2...
"
Then we execute two SQL queries to enter two names in the database. Note that the database field 'name' does not allow two identical names.If ErrorsFound(con) = False Then
con.CommitTrans
Response.Write "Committing Transaction...
"
Response.Write "Records added successfully...
"
Else
con.RollbackTrans
Response.Write "Rolling back transaction...
"
Response.Write "Records were not added...
"
End If
Next we use the ErrorsFound Function that we created earlier to check if any errors occured, if not then commit the transaction, otherwise do rollback.
Then we close the connection and show the error message ( if any ) and then the records.
The point to note is that the two queries we ran as a transaction will only be executed if no database errors occur, if they do then the queries will be rolledback and no changes will be produced in the database.
Running the ASP pageYou should place both the db.mdb and trans.asp files in the same directory. Assuming that you placed both of them under /trans/ directory under your virtual directory, you should use http://127.0.0.1/trans/trans.asp URL to see your ASP page on your local computer.
Notice the database error and how it is displayed. At the bottom, all the records inserted so far are displayed in a tabular fashion.
What we learned ?We built an ASP page which uses ASP-Database transactions to either execute all of the queries or none at at all depending on the condition that any database errors are produced or not.
We also built a very useful Function which you can use to track database errors and display them in a feasable way to the user. Not only this function allows to show database errors if you want, you can use it transparently without showing any erros to check if any database errors occured or not and then committing and rolling back the transactions accordingly.
DSN vs DSN less Database Connections
In this article we will learn the two ways of connecting to database :
via DSN ( Data Source Name ) without DSN DSN ConnectionsIn my earlier article on Accessing the database from ASP I explained connecting to database via DSN in a step by step mannner. So there is no need to repeat that again, you can see it from there.
DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone e.g Excel spread sheet etc.
I will now skip the steps of creating and assigning DSN to a database, you can see them by clicking here. Once you are done creating a DSN for your data source ( database lets say ), you can connect to it using following code :
Dim con Set con = Server.CreateObject("ADODB.Connection")
con.Open "DSN=mydsn" ' Now database is open and we are connected ' Do some thing
here 'We are done so lets close the connection con.Close Set con = Nothing
ExplanationIf you have been following my tutorials then above code will be nothing but a piece of cake for you. The only significant point to see is that we have used "DSN=mydsn" to connect to our database using our DSN which in this case is mydsn.
DSN less ConnectionDSN less connections don't require creation of system level DSNs for connecting to databases and provide an alternative to DSNs. We will now see how to connect to a database via ASP using Connection String in place of DSN name.
Dim con Set con =
Server.CreateObject("ADODB.Connection")
con.Open
"Provider=Microsoft.Jet.OLEDB.4.0; Data" &
_ "Source=c:\path\to\database.mdb"
' Now database is open
and we are connected ' Do some thing here 'We are done so lets close
the connection
con.Close Set con = Nothing
ExplanationThe only change is use of a Connection String in place of a rather easy to remember DSN. Above code connects to an imaginary Access database. Connection Strings for other databases are different.
How to construct a Connection String for Access and SQL Server Databases ?
For Access database :-With native OLE DB Provider ( preferred ):Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\path\to\database.mdb
Using ODBC connection without specifying a DSN :Driver={Microsoft Access Driver (*.mdb)}; DBQ=c:\path\to\database.mdb
Note, always use the first Connection String that uses native OLE DB provider because it is faster than the second one. 'Data Source' or 'DBQ' are absolute path to the database. If you have relative path then you can obtain absolute path by using Server.MapPath("/relative/path/to/database.mdb") e.g.
Dim conStr Set conStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("/dbo/database.mdb")
For SQL Server :With native OLE DB Provider ( preferred ):-
Provider=SQLOLEDB; Data Source=server_name; Initial Catalog=database_name; User Id=user_name; Password=user_password
Using ODBC Provider :Driver={SQL Server}; Server=server_name; Database=database_name; UID=user_name; PWD=user_passwordWhy to use DSN Connections ?
Provides easy to remember data source names. When there are lots of data sources to think of and you want a central repository to hold the collection of data sources without having to worry about the actual site and configuration of the data sources. Why to use DSN less Connections ?
When you can't register DSNs yourself e.g. when you are running a virtual hosting account on other's server. Stop emailing system administerator, connect to your databases directly. Provides faster database access because it uses native OLE DB providers, while DSN connections make use of ODBC drivers. My ExperienceI always use DSN less connections on my site and examples :).
Displaying Images from an Access Database using plain ASP
That article described how to upload a binary file via ASP into the database. In this article I am going to talk about the second part, displaying that binary data from the database.
File Uploading with ASP.NETIf you have the privilege of using ASP.NET then you should read these comprehensive tutorials regarding file uploading using built-in ASP.NET server controls:
File uploading to server hard disk. File uploading to Microsoft Access database. Uploading images, determining size, width & height and resizing image files. In the 1st article I deliberately left two files, show.asp and file.asp Those two files are going to be the ones we create in this article.
Show.aspOpen notepad and create a new file. Name it as show.asp. Copy the following code and paste it into the newly created show.asp file and hit the save button :
' -- show.asp -- ' Generates a list of uploaded files Response.Buffer = True ' Connection String Dim connStr connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("FileDB.mdb")
Showing Binary Data from the Database
To insert data click here
| " Response.Write "No. of records : " & rs.RecordCount Response.Write ", Table : Files " Response.Write " | ||||||
| " Response.Write rs("ID") & " | " Response.Write "" Response.Write rs("File Name") & " | " Response.Write rs("File Size") & " | " Response.Write rs("Content Type") & " | " Response.Write rs("First Name") & " | " Response.Write rs("Last Name") & " | " Response.Write rs("Profession") Response.Write " |
' -- show.asp --' Generates a list of uploaded files Response.Buffer = True
Set the buffering of the show.asp page to True.
' Connection StringDim connStr connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("FileDB.mdb")
Next we declare a variable connStr as our connection string and set it's value to the path of FileDB.mdb database. Note that FileDB.mdb is the database we have been using to store binary data.
show.asp
' Recordset ObjectDim rsSet rs = Server.CreateObject("ADODB.Recordset")
' SQL StatementDim sql_selectsql_select = "SELECT [ID],[File Name],[File Size],[Content Type] "sql_select = sql_select & "FROM Files ORDER BY [ID] desc"
' opening connectionrs.Open sql_select, connStr, 3, 4
We create a Recordset object and run a SELECT query to retrieve all the records from the Files table.
If Not rs.EOF ThenResponse.Write "
"Response.Write "
If the retrieved Recordset is not empty, meaning that there are some records in the Files table, we write the headers of an HTML table to show these records.
While Not rs.EOFResponse.Write "
rs.MoveNextWend
Using a While...Wend loop we display all the records in the Files table.
ElseResponse.Write "No Record Found"End If
rs.CloseSet rs = Nothing
If the Recordset was empty, meaning there are no records in the Files table we display a "No Record Found" message. Next we close the connection to the database and Set Recordset object to Nothing.
Notice that in the all the records that we displayed we linked each record to file.asp page, file.asp is going to be the actual file to display binary records from the database.
file.aspOpen notepad and create a new file. Name it as file.asp. Copy the following code and paste it into the newly created file.asp file and hit the save button :
' -- file.asp -- ' Retrieves binary files from the database Response.Buffer = True ' ID of the file to retrieve Dim ID ID = Request("ID") If Len(ID) < 1 Then ID = 7 End If ' Connection String Dim connStr connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("FileDB.mdb") ' Recordset Object Dim rs Set rs = Server.CreateObject("ADODB.Recordset") ' opening connection rs.Open "SELECT [File Name], [File Data], [Content Type] FROM Files " & _ " WHERE ID = " & ID, connStr, 2, 4
If Not rs.EOF Then Response.AddHeader "Content-Disposition", "filename=" & _ rs("File Name) Response.ContentType = rs("Content Type") Response.BinaryWrite rs("File Data") End If rs.Close Set rs = Nothing
Explanation
' -- file.asp -- ' Retrieves binary files from the database
Response.Buffer = True
' ID of the file to retrieve Dim ID ID = Request.QueryString("ID")
Sets the buffering to True. Next we create a variable named ID and set it's value to the Request.QueryString("ID").
' Connection StringDim connStr connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ Server.MapPath("FileDB.mdb")
Next we create a connStr variable as the connection string to the database and set it's path to FileDB.mdb database.
' Recordset ObjectDim rs Set rs = Server.CreateObject("ADODB.Recordset")
' SQL SELECT Statement Dim sql_select sql_select = "SELECT [File Name], [File Data], [Content Type] " sql_select = sql_select & "FROM Files WHERE ID = " & ID
' opening connection rs.Open sql_select, connStr, 2, 4
Create a Recordset object and run a SELECT statement to retrieve the File Name, File Data and Content Type of the given file.
Note that File Data field contains the saved binary data for the file, while Content Type field contains the content type for the file. We need both of them to display the file. The "Content-Disposition" header is necessary to send the file with the correct name back to the browser.
If Not rs.EOF Then Response.AddHeader "Content-Disposition", "filename=" & _ rs("File Name) Response.ContentType = rs("Content Type") Response.BinaryWrite rs("File Data")End If
If Recordset is not empty i.e, there is a file with given ID, then we set the Content Type of given ASP page to file's Content Type. Next we use Response.BinaryWrite method to write the binary data to the client browser. The file will thus be shown to the client.
rs.Close Set rs = Nothing
We close the connection to the database.
On the next page I summarize the steps involved in displaying binary data from the database.
SummaryThis article was second in the series of articles about manipulating binary data via ASP and storing it in the database. In this article we built files which were missing in the ASP-Database file uploader application in the first article. show.asp simply displayed a list of all the files in the database. file.asp was the actual file which will send the binary data back to the client.
You must have noticed that how easy it is to write binary data from the database via ASP to the client. There are two things to keep in mind while doing that. First, always properly set the Content Type of the page using Response.ContentType property. Secondly, use one ASP page to display only ONE file like we did with file.asp. And that page should not write anything else to the browser i.e, don't try to write text in an ASP page as we do in other ASP pages when you've already used the Response.BinaryWrite method.
Well that's it for this article. You should continue your reading and read the other two articles of this series; "inserting binary data to the database" and "uploading binary data ( files ) to the server hard disk". That'll be enough.
Adding records to the database with ASP
Adding records to the database with ASP
Overview
No matter what kind of site you have got, you will need your ASP pages to access databases. ASP makes it easier to work with databases by providing support for ADO ( Activex Data Objects ). You already know how to build DSN ( Data Source Name ) and then access database, if you don't then you might want to check out my tutorial on Accessing Databases via ASP.
In this article I will build on that tutorial to show you how to add records to the database. We will begin by exploring the insert statement provided by SQL ( Structured Query Language ). After that we will see the two basic ways we can use to add records to the database.
I will assume here that you have read the Accessing Databases via ASP tutorial and are comfortable creating DSNs and simple Access Databases. I will also assume that you have got access to Microsoft Access Database, PWS / IIS with a notepad to write ASP pages.
SQL Insert StatementSQL is the standard language to deal with databases World wide. It provides us with select, insert, delete and update statements to show, add, delete and update the records in the database respectively. We will only study the insert statement since we are only dealing with adding records to the database here. It will be very helpful to us when we are adding records, as we'll see later.
Syntax
insert into table_name (field1, field2, field3) values ('value1',
'value2', 'value3';
The insert statement as you have seen above is very simple to understand. It takes three arguments; table, fields and values. table_name is the name of the table in the database into which you want to add records. fieldn are the names of the columns in that table into which you want to add records. valuen are the values which will be inserted into specific fields. Note field names and values can be one or more than one but the table name will always be one.
Example
insert into books (author, title) values ('Faisal Khan', 'Add
Records';
When run the above query results in the insertion into two fields of table books, author and title values Faisal Khan and Add Records.
Table Name =
books Fields Values author Faisal
Khan title Add Records
Now after you are familiar with the insert statement and have seen how it works, it is time to move forward to see the two ways by which we can easily add records to our database via ASP.
We manipulate databases in ASP through ADO ( Activex Data Objects ). ADO is a set of pre made data components which makes things a lot easier for us when it comes to accessing data stores. Wondering why did I say data stores and not databases ? well, database is only one of the data stores and ADO can help us access more than that e.g. XML. We'll not go into what ADO can do for us, instead we'll restrain ourselves to the discussion of adding records to database via ASP.
There are two ways to add records to the database. We'll discuss each of them now.
Via Connection ObjectIt is the easiest and fastest way to add records to the database.
Here is how we add records with Connection Object :
' Setting
variables Dim con, sql_insert, data_source
data_source =
myDSN sql_insert = "insert into books (author, title) values " &
_ "('Faisal Khan', 'Adding Records')"
' Creating the
Connection Object and opening the database Set con =
Server.CreateObject("ADODB.Connection") con.Open data_source
'
Executing the sql insertion code con.Execute sql_insert
' Done.
Now Close the connection con.Close Set con = Nothing%
The above results in the creation of Connection Object which opens the database and inserts the records into specific fields of the table according to the SQL insert statement. See, didn't I say before it was going to be easy.
Via Recordset ObjectRecordset is another very useful Object which allows us to select, add, update and delete records without using SQL statements. Here is how we add records with Recordset Object.
' Setting variables Dim rs, data_source
data_source =
myDSN
' Creating Recordset Object and opening the database Set rs
= Server.CreateObject("ADODB.Recordset")
' Lets open books
table rs.Open "books", data_source
rs.AddNew ' Now adding
records rs("author") = "Faisal Khan" rs("title") = "Adding
Records" rs.Update
' Done. Now Close the
Connection rs.Close Set rs = Nothing
We didn't use any SQL insert statement here but added the records.
So what should you use ? Connection or Recordset Object, for adding records. Well Connection Object is fast and uses less server resources while Recordset Object is resource heavy. So if you have to add records to the database then Connection Object is usually the preferred way. Whichever you choose is up to you.
Accessing database from an ASP page
Databases are a way of organizing and keeping your data. The data stored in databases can be anything from user email addresses to binary files. Databases have become so popular in the past decade that it is almost unimaginable to not to use them on the web.
In this tutorial I will guide through the creation of a simple Microsoft Access database to incorporating it in to your ASP web pages. Creating and making use of a database on the web is so very much easy that it will be only after reading this article you will realize the same and will then hopefully start creating databases according to your own needs and then playing with them from the web pages.
Requirements
You are required to have Microsoft Access database ( any version will do the trick, 97, 98 2000 ), MDAC 2.0 or above ( latest is MDAC 2.5 ), either PWS 4 or IIS 4.0, Windows platform and a web browser. Don't worry if you don't know about MDAC ( Microsoft Data Access Components ), you can check if you have already got them by going to Start -> Settings -> Control Panel. There you will find a small icon 'ODBC 32'. If you can see the icon then you have got MDAC but if you cannot find the icon then you will most probably have to download them from Microsoft's site. If you are running Windows2000 Professional then you can find the "Data Sources ODBC" icon in the "Administrative Tools" section of the control panel. For displaying our database contents on the web browser we will be using Microsoft's Active Server Pages technology. For that either PWS 4 or IIS 4 ( or above ) will be required. Both of them are free and can be downloaded from www.microsoft.com.
As you would have most probably guessed by now, I am assuming that you are a newbie and don't know much about this stuff. So if you have got what it required ( above ) then we are ready to move on to the tutorial.
In the next few pages we will create a simple Access database and add some content to it, then create a ODBC System DSN for it and show the contents of that database on our web page. The tutorial is pretty much simple and you will learn a lot from it, so I advise you to go through the next pages one by one and complete each page's tasks. Good luck!
Ok, we begin by creating a simple Access database.
Step 1 : Start Microsoft Access by clicking 'Microsoft Access' icon in the Program Files menu. Start -> Program Files -> Microsoft Access.
Step 2 : Microsoft Access will start with default windows opening up at start up. Click 'cancel' to exit any windows that appear.
Step 3 : Click the File -> New button at the top left main windows of Access. This will bring up a 'New' dialog box window. Of the two tabs click the 'General' tab and then the 'Database' icon. This will select 'Database', then hit the 'OK' button.
Step 4 : This will bring up 'File New Database' dialog box. It will ask for the database name and location to store that database to. Type 'odbc_exmp' in the 'File Name' input box and give it any location to store that database to. For this tutorial we will assume that our database 'odbc_exmp.mdb' was saved at c:/stardeveloper/db/odbc_exmp.mdb . Then hit the 'Create' button.
Step 5 : Our database 'odbc_exmp.mdb' is now created. But it is empty and we will need to populate it a bit so that we can later use it. In the Microsoft Access, you will now be seeing a 'odbc_exmp : Database' dialog box showing quite a lot of options on the left column and three options in the right column. Double click the 'Create table in Design view' option in the right column.
Step 6 : This will bring up 'Tabe1 : Table' dialog box. Just in case if you don't know, data is stored in tables in a database. There can be many tables within one database. Tables in turn consist of Fields ( columns ) and rows ( records ). Fields ( columns ) do not accept accept data of all type. We have to specify the data type that a Field ( column ) will hold and then we can add records for that data type in the rows. It is this 'Design View' in Microsoft Access that is used to specify the number of columns our table will have and what data type that Fields ( columns ) will hold. Ok now type the 'Field Names' and 'Data Types' exactly as shown below. Note that you can select 'AutoNumber' and 'Text' from the drop down options in the 'Data Type' column as required. There is no need to edit any values in the 'General' and 'Lookup' tabs in the 'Field Properties' section of the 'Table Design View'. Now click the File -> Save button. A 'Save As' dialog box will prompt you to enter the name for this table, type 'names' in that dialog box and hit 'OK'.
Step 7 : Close the 'names' table design view window. Now you will see 'names' table being added to the right column of the 'odbc_exmp : Database' window. Double click the 'names' table. This will bring up the 'names : Table' window showing an empty row and three columns with 'Field Names' which we specified earlier. It is used to add data to the table. We will add five names to our 'names' table. There is no need to add anything to the 'id' Field as it will autoincrement one number upon the addition of records to the rows one by one. If you don't understand what I mean by autoincrementing then just leave this field for a moment and you will come to know what it does later when we add records. Ok now add five names ( first, last ) in the empty row under their respective Field Names as shown below.
See the numbers in the 'id' Field. Thats what autoincrement does. It adds the numbers in a sequential way. Now hit the 'save' button to save the records which we have added in our 'odbc_exmp.mdb' database. This completes our task of creating a simple Access database.
You have just seen that how easy it is easy to create a database. You have also learned what are tables, rows and columns. You have also learned what 'Data Types' are and how to specify a 'Data Type' in the table column. You have also added records to the database. Now we will move forward and will register our database in the System registry by assigning it a Data Source Name ( DSN ). Well done, now continue to the next page.
DSN stands for Data Source Name. Data source can be a database, spreadsheet, text file etc. We assign DSN to a data source so that irrespective of the data source details and location, we can use that data source; add, modify or delete records, just by knowing it's DSN.
To assign DSN to our 'odbc_exmp.mdb' database, follow the steps below :
Step 1 : Open 'Control Panel' ( Start -> Settings -> Control Panel ). Double click the 'ODBC 32' icon. If you are running Windows2000 then double click the 'Administrative Tools' icon in the 'Control Panel' and then double click the 'Data Sources (ODBC)' icon. If you cannot find the 'ODBC 32' or 'Data Sources (ODBC)' icon then please see the discussion at the start of this tutorial.
Step 2 : By double clicking the 'ODBC 32' or 'Data Sources (ODBC)' icon on Windows2000 a window 'ODBC Data Source Administrator' will appear. It will contain many tabs on the top e.g. User DSN, System DSN, File DSN and so on. As far as ASP ( Active Server Pages ) are concerned, we will use System DSN. Click the 'Add' button. A window will appear like below :
Step 3 : Select the Microsoft Access Driver (*.mdb) from the list and hit the 'Finish' button.
Step 4 : You will now see another dialog window asking you the location and name of your new Microsoft Access database. In the 'Data Source Name' field type 'odbc_exmp' and then hit the 'Select' button. Now browse to the location where you have saved the 'odbc_exmp.mdb' database we created earlier. Once you find the location select the 'odbc_exmp.mdb' name and then hit ok. You will eventually see 'ODBC Microsoft Access Setup' dialog box like below :
Click the 'OK' button in the window above. You will now get back to your System DSN windows. You will now see odbc_exmp added to your System DSN list. We have successfully created a System DSN for our 'odbc_exmp.mdb' database.
In this chapter you saw how easy it is to assigning DSN to a database. In the next chapter we will create a simple .asp page in which we will show the contents of our 'odbc_exmp.mdb' database.
We have created a database and assigned it a DSN, we will now show our database's contents on our web page using Microsoft's Active Server Pages technology. Active Server Pages or simply called ASP are pages which use a server side scripting language e.g. VBScript, to bring dynamic content to a web page. All of the processing is done on the server side and then output is generated like an ordinary HTML page which any browser can understand and view. We will not go into details of ASP in this tutorial but will only touch those parts of ASP which will help us understand how to access a database from ASP.
Step 1 : Open Notepad ( Start -> Program Files -> Accessories -> Notepad ). Copy the code below and paste it into your Notepad. Don't worry if you cannot understand what this code is doing. I'll explain that in a moment, for now just copy all the code below to your Notepad.
Step 2 : After pasting the above code into your Notepad, save this page as 'odbc_exmp.asp' and give it any location where you can run .asp pages, usually in PWS/IIS that location is c:/Inetpub/wwwroot/ .After saving the file and giving it above location you can see it in your browser.
Step 3 : Start the PWS ( or IIS ) if it's not already running. Now open your favorite browser and type the following in your URL box of your browser :
http://127.0.0.1/odbc_exmp.asp
Note that above URL will only work if you have saved the 'odbc_exmp.asp' file at c:/Inetpub/wwwroot/ ( or where ever your wwwroot directory is present ). If you have put it in a 'temp' directory e.g. c:/Inetpub/wwwroot/temp/ then the URL to put in your browser URL box will be 'http://127.0.0.1/temp/odbc_exmp.asp'. Ok after putting the above URL in your browser URL box hit enter. If all id done right you will see a list of first and last name along with their IDs of all the entries ( five ) we made in our 'odbc_exmp.mdb' database. If you can see the following you are done.
ID : 1
First Name : Faisal
Last Name : Khan
ID : 2
First Name : John
Last Name : Lee
ID : 3
First Name : David
Last Name : Doshambey
ID : 4First Name : Marvin
Last Name : DeboyID : 5
First Name : MichaelLast Name : Chang
If you know some HTML then you would have guessed that in our code ( see above ) all of the tags are simple HTML tags except tags. Every thing inside the tags is the ASP code. We will now simply touch the ASP code we wrote to help you understand how we were able to output database content on our web page.