|
by Derrald Farnsworth-Livingston
Technical Setup Stuff In this document we will discuss the ability to access SQL Server databases through Visual Basic commands, both in Visual Basic programs and Visual Basic Script. In order to begin a Windows NT 4.0 Server machine must be installed. SQL Server must then be set up on this machine. Internet Information Server 4.0 (3.0 will work, but the drivers must be installed) must also be configured.
Odie B What? ODBC stands for Open DataBase Connectivity (ODBC). This is an Application Programming Interface (API) that allows for data extraction from a database through a unified source. In the past it was difficult to extract information from various databases. Each had its own language that had to be coded. If a user wished to switch databases the program normally had to be recoded. Now, the job of accessing several different databases is simplified. One must only program in the ODBC language that is a combination of the ODBC API function calls and SQL (Structered Query Language). Most databases now support this standard and all that is needed to interact with various databases is the correct ODBC driver for the database and knowledge of SQL. To begin accessing various databases, the correct driver must first be installed. The Microsoft Access, dBase, FoxPro, and SQL Server drivers are the standard drivers installed with Windows NT Server. Drivers for various other databases such as Sybase, Informix, and Lotus Approach are easily attainable. Once the correct driver is installed a DSN (Data Source Name) must be configured to access a particular database. One can either set up a System DSN or a User DSN. The User DSN only allows the creator of the DSN to access the database through the data source. In order for multiple users on the machine to access a particular database either multiple User DSNs or a System DSN must be configured. A System DSN allows all the users of a machine to access the database through that data source. We can set up a sample DSN easily in either Windows 95/98 or Windows NT. First we go to the ODBC control panel. We then choose the System DSN tab. Click on Add and choose Microsoft SQL Server driver. Click the next button. Next we are prompted to enter some information for the data source. The name we will use for the Data Source will be Students. The Description can be anything. The Server that we will use is BUBBA. If you are using the 2.x version SQL Server driver for Windows 95/98/NT we must click the options button at the lower right corner of your dialog box. Under database name type Sample. Then click ok. Windows 95/98/NT ODBC Version 2.x users are now finished. If you are using SQL Server driver version 3.x Windows NT you must click the next button. This prompts you for login information. Choose the radio button next to "With SQL Server authentication using a Login ID and Password entered by the user". The text boxes at the bottom of the dialog box now become enabled. Under Login ID type sa and leave the password field blank. Click the next button. We must now choose the database that will allow us to access the table that we want. Here we have a list of database objects retrieved from the SQL Server. Choose sample and then click the next button. Click the next button once again, leaving the default settings. If you wish to keep a log of the SQL queries set up the path and file names, otherwise do not enable this option. Now we can click the finish button. Our DSN is now set up. One nice feature of the Windows NT ODBC manager over the Windows 95/98 managers is that we can now test the datasource to see if it correctly connects with our database. We can do that now by clicking "Test Data Source". We have now set up an ODBC Data Source to interact with a database on a Microsoft SQL Server.
You Gotta Love SQL Once either the User or System data source has been configured we can begin creating programs utilizing SQL to access a databases. The reference to SQL can either be pronounced S Q L or Sequel as tribute to the first relational database language actually known as Sequel. SQL (Structured Query Language) is a language standard for querying and manipulating databases. It allows for programmers to easily switch between various databases by standardizing the commands needed to perform the necessary tasks. SQL is comprised of fairly basic, straightforward commands that can be used to accomplish complex events. The language is broken up into threeparts, DDL (Data Definition Language) which creates, modifies, and deletes tables, DML (Data Manipulation Language) which works with the actual data contained in the databases, and DCL (Data Control Language) which controls security on database objects. SQL is a case-insensitive language, but most of the time the SQL commands will be coded in uppercase letters to distinguish it from the data and surrounding code. Retrieving Data from the Database Here is a simple command that will pull only the first name and last name of the students in a particular database.
If we wish to qualify the list so that only students from Omaha are returned we add the WHERE command. This selects all the students from the database WHERE the city field is Omaha. The ORDER BY command will place the selected entries in alphabetical order first by their last name and then by their first. SELECT firstname, lastname FROM students Adding Data to the Database Before we can retrieve data from the database, we must have data populating the database. Here is a simple command for inserting data into the SQL database: INSERT INTO Students (lastname, firstname) The values of John and Smith are placed in the Students database in the lastname and firstname fields. If the values of "John" and "Smith" were reversed they would not be placed in the correct fields in the database. The field order must correspond to the value order. Deleting Data from the Database Deleting data from the database is an easy task as well.
All the students that have a graduation date of 1999 will be deleted from the Students database. Updating the Database Old Value: ShotneyNew Value: Chuney UPDATE Students In this instance someone had mistakenly misspelled Chuney’s name as Shotney. To correct this error an update needed to occur as evidence by the UPDATE SQL command. This only works, however, if there is only one member in the database with the last name of Johnson. If there are multiple instances of "Johnson" in the database then it would update all the first name fields of all the Johnsons. To make sure that this type of error does not occur a primary key field must be identified. A primary key field is a field that can only correspond to one record. A good primary field key to set up in the case of a student database would be the Social Security field. The commands that control creating databases, deleting databases, deleting all the information contained in a database are also very simple SQL commands. Back to the BASICs Ok, so we all remember the Commodore 64s and Apple IIs and whatever else we had when we were younger on which we sometimes programmed. The code looked something like this: 100 Print "Hi" Well, BASIC has improved and has now become Visual. One of the three great strengths of Visual Basic is the ability to easily write programs. Well, I guess that was always a strength. Another strength of Visual Basic is the ease of connecting to databases. Access, FoxPro, SQL Server, you name it and chances are there is some way you can easily write a few lines of code to obtain data from these databases and utilize it within your programs. The two ways of connecting to databases are through the Microsoft Jet engine or through ODBC. The type of connection we will be focusing on is ODBC. Since we already have a working knowledge of SQL and we know how to set up a data source we can start writing programs with Visual Basic to access a database. Code, Code, Code We will assume that the SQL Server has been correctly set up and that a database has already been created for us. The database name will be "Sample" and the table name that we will be accessing will be "Students". We will also utilize the DSN that we created earlier. There is one more setting that we must work with before we begin. We must enable the DAO Object Library. This controls the database access object code that we will be using, such as workspaces and recordsets. We can accomplish this by selection Project from the menu and then references from the list. We then put a check by "Microsoft DAO 3.51 Object Library". The first piece of code that is important to database connectivity through Visual Basic is the code that sets up the workspace. The workspace defines how your program will interact with the data from the database. It also sets up whether the connection type will be Microsoft Jet or ODBC. First we set up the variable and define it as a workspace.
Dim wrkODBC As Workspace Next we set the variable to create a workspace with the name of ODBCWorkspace. The second field in the CreateWorkspace function refers to a username and the third to a password. These are used if you want to set up a user and a password to access the workspace. (See UserName for more information). The last field refers to the type of connection we want to make, in this case ODBC.
Set wrkODBC = CreateWorkspace("ODBCWorkspace", "", "", dbUseODBC) After correctly setting up the workspace we can now make the connection to the database. Again we must set up the variables to access the database.
Dim X As String Now we can set up the connection to the database which will occur within our Workspace. Here we are setting the StudentDatabaseConnection to be opened in the wrkODBC workspace. The first field refers to the fact that we are opening the database "Students". The second field refers to options that can be set up within the connection. The third field is a boolean value that is used to show whether the database should be opened as read-only or not. The last field refers to the connection. The connection here is declared by the variable X. It is the information needed to connect to the DSN (Students) we previously set up and to the database (sample) defined in the SQL Server itself.
X="ODBC;database=sample;DSN=Students;UID=sa;PWD=" Once we have created the needed connection we can then create a variable to access the table from the database as a recordset. Using the variable that we set up as the connection we then use the function "OpenRecordset". The first field in this function refers to the table within the database we would like to open, in this case "Students". The second field refers to the fact that we wish to open this table for dynamic (or read/write) use. Other options are Read-Only and Forward-Only.
Set StudentDatabase = StudentDatabaseConnection.OpenRecordset("Students", dbOpenDynamic) We could have set up the StudentDatabase like this as well, however many of our SQL Queries occur with the Connection, not on the Recordset.
wrkODBC.OpenConnection("Students", , False, X).OpenRecordset("Students", dbOpenDynamic) We can now start performing SQL queries on the table within the database. We can begin with a simple insert function that will allow us to add data to the table. Currently, the fields that are contained within the table are: SSN, Firstname, Lastname, Major, GradDate. We will set up five text boxes within our Visual Basic form to enter the data. They will be referenced as txtSSN, txtFirstname, txtLastname, txtMajor, and txtGradDate. To enter the query into the database a string variable, SQLStmt is defined. The variables that are contained within our Visual Basic program must be placed into the SQLStmt string so that they can be processed in the query. To accomplish this task we first add a single quote, a double quote, and then an ampersand. We then add the variable name and then finish it with an ampersand, a double quote, and a single quote. This shows that the variable value, not the variable name is to be placed into the table. To make strings longer, such as SQL queries so they do not run off the page. We can begin the SQLStmt and then add to it with the use of SQLStmt = SQLStmt & String. In this way we can build strings, such as querys with multiple lines. We should set up a button, cmdSave that will run this function.
Dim SQLStmt As String Once the statment has been formed we must run the query against the table. We accomplish this with the command:
StudentDatabaseConnection.Execute SQLStmt Notice that it is the connection, not the recordset that executes the needed command. Now that we have information in the database we are ready to retrieve that information. Since we have already written a function to make a connection to the database if we run that function again, it will refresh the table information. We can then load the database information into the textboxes we have already set up.
txtSSN.Text = StudentDatabase.Fields("SSN") We are retrieving the information through the recordset, not through the connection which we used to execute our queries. Suppose we want to move through the various records. This can be accomplished with the Visual Basic functions .MoveNext, .MovePrevious, .MoveFirst, and .MoveLast. To move to the next field we can set up a button that corresponds to a function that runs this code:
StudentDatabase.MoveNext We should set up four buttons to accomplish these tasks, cmdNext, cmdPrevious, cmdFirst, and cmdLast. Now that we can move through the fields we may wish to delete records within the database. The following function will delete an entire record (SSN, Firstname, Lastname, Major, and GradDate) based upon our primary key, or the Social Security Number. We need to set up a button, cmdDelete that will run this function.
Dim SQLStmt As String The last thing we will add to our program is the Exit command. When we exit the program we must end our connection to the recordset and database. This can easily be accomplished with these two lines of code:
StudentDatabase.Close We have now completed our rudimentary Visual Basic program to access a database through ODBC on a SQL Server. We can add, delete, and peruse records. Other function, such as update and creation of database tables can be added easily later. One more acronym please! Remember I said that there are three strengths to BASIC, and I only mentioned two. Well, here’s the last and a very important one. Within the last couple of years a language has beendeveloped known as Visual Basic Script, or VBScript that can run programs through web browsers such as Netscape, Opera, and Microsoft Internet Explorer. This makes it easy to transport some programs developed in Visual Basic to the web and vice-versa. Not all features are supported in VBScript. For instance the ability to read and write files through the web browser is extremely limited so that violations of security, viruses are more difficult to program and are not as frequent. Database programs, however, are easy to transport and benefit the most in conversions. This allows for data in a database is now accessible worldwide instead of companywide. How do I do it? VBScript is readable by web browsers as ASP (Active Server Page) files on a Microsoft Internet Information Server (version 3.0 and later of course). Instead of index.html we now have index.asp. The languages that we must be familiar with also now change. We must still be familiar with Visual Basic (ok, actually VBScript) and SQL, however, we just added HTML (Hyper Text Markup Language). Note: HTML is a fairly simple language to learn. If you would like more information, there are many good primers on the web. In Visual Basic we have forms, now our forms in a small sense become web pages written in HTML. The way it works is that the scripts are executed and it sends the information to the web browser in HTML form. None of the scripting language source is viewable when it is sent, only the HTML. For instance, here is an extremely short ASP program that will demonstrate the HTML output. <%@ LANGUAGE="VBScript" %> <%When run in your web browser this output will result: Hello If you choose to view the source the code looks like this: <font size=1>Hello<br></font> <font size=2>Hello<br></font> <font size=3>Hello<br></font> <font size=4>Hello<br></font> <font size=5>Hello<br></font>The code at the beginning: <%@ LANGUAGE="VBScript" %> denotes that the language that will be used within this ASP is Visual Basic Script. This line must be the first line of the code. The script part of this page is contained within the <% %> brackets. The HTML is the rest of the surrounding code. The value of the variable i is printed in HTML by using the <%=i%> command. It is important to note that in Visual Basic Script all variables are variants. This means that no variable can be defined as a integer, string, etc.
Bring on the Databases Like I said before one of the greatest functions of Visual Basic is its ability to work with databases. VBScript is also very easy to set up to access and perform database operations. Once again we begin by setting up the variables and connection to the database.<%@ LANGUAGE="VBScript" %>
<%
Option Explicit
Dim Connection
Dim RS
Dim SQLStmt
Dim SSN, Firstname, Lastname
Set Connection = Server.CreateObject("ADODB.Connection")
Connection.Open "DSN=Students; UID=sa"
The Connection variable is set to the ADO (Access Data Object)
Connection type object. Once that has been set we can open the connection
through the same DSN that we set up earlier. There is no need to duplicate
the ODBC data source. Now we can set up our SQL query exactly the same way
it would appear in Visual Basic. This query will select all in the
information contained in the social security number, first name, and last
name fields in the database and then order it in alphabetical order by
lastname. SQLStmt = "SELECT SSN, Firstname, Lastname " SQLStmt = SQLStmt & "FROM Students " SQLStmt = SQLStmt & "ORDER BY Lastname "We then set the variable RS to execute this SQL Query which is similar to the OpenRecordset function of Visual Basic. Set RS = Connection.Execute(SQLStmt)<br> %>Following this we have the written the page in normal HTML. This simply sets up the look of the beginning of the page before the data is sent from the database. <html> <title>Administration Student Update</title> <BODY BGCOLOR="FFFFFF"> <hr> <font size=2> <h1>Student Information</h1> <h2>Here are the students in the Database.We then set up a Do/While loop to go through all the records in the database until EOF or the last record has been reached. This is accomplished by using the RS variable with the .Fields reference. The records are moved through by utilizing the .MoveNext function. <%Do While
Not RS.EOF%> Name:<ahref="details1.asp?SSN=<%= RS.Fields("SSN") %>">We then finish the page with normal HTML and we close the
connection. <hr> </body> </html> <% Connection.Close %>In a few lines of code we have written a program to pull data from a SQL Server database. One thing you may have noticed is the ? after the hypertext link to the file details1.asp. This sets up a query string within the link. A query string sends data through the URL location (basically the address of the page) to the next page that can interpret this information. In this case the string that is sent becomes SSN=A Social Security Number in the database. Example: SSN=123456789. By taking a look at details1.asp we can see how the information is used. <%@ LANGUAGE="VBScript" %>
<%
Option Explicit
Dim UID, SQLStmt, Connection, FirstName, LastName
Dim RS, SSN, Major, GradDate
SSN = Request.QueryString("SSN")
Set Connection = Server.CreateObject("ADODB.Connection")
Connection.Open "DSN=Students; UID=sa"
SQLStmt = "SELECT * "
SQLStmt = SQLStmt & "FROM Students "
SQLStmt = SQLStmt & "WHERE SSN = '" & SSN & "' "
Set RS = Connection.Execute(SQLStmt)
%>
<html>
<title>Administration Student Update</title>
<BODY BGCOLOR="FFFFFF">
<hr>
<font size=2>
<h1>Student Information</h1>
<% Do While Not RS.EOF%>
<h2>Here is the Student Information for The value of the variable of SSN in the query string was passed onto
this page and then placed in the new Visual Basic script variable SSN by
the function Request.QueryString. It was then processed in a SQL Query and
more information on the record was extracted from the database.
By using query strings information can continually be passed between web pages on a site so that information can be retained. One of the many beauties of ASP is that the web pages will never increase in size as the database grows as they are dynamic. Data can change and the outputted web pages will change, but the original ASP files will stay the same. Another plus about ASP is that if the script is run on the server as all the scripts demonstrated do, the programs can be used on various platforms. As long as the browser can read the HTML, there is no limit on operating system or machine. Also, since all the ASP files are generally in one location all the files can be updated easily, so there are no patches or version updates that need to be released to customers. ASP is currently being used on E-Commerce sites and other database sites and it is quickly growing. One example is http://www.headhunter.net/. |