Vb6 and SQL Tutorial
Vb6 and SQL Tutorial
Vb6 and SQL Tutorial
No matter what programming language you use at some point and time you will need to access a database. While you don't have to be a database whiz you should at least, know the basics of working with databases. The first thing you will need to understand is the basics of SQL (Structured Query Language ). SQL allows users to access data in relational database management systems, such as Oracle, Sybase, Informix, Microsoft SQL Server, Access, and others, by allowing users to describe the data the user wishes to see. SQL also allows users to define the data in a database, and manipulate that data. This tutorial is not a Database programming or Database Design tutorial. Its purpose is to give you a basic understanding of SQL so you can work with databases in your applications. Whether your language of choice is VB, C/C++ or Java. Or your database of choice is Access, Oracle, Microsoft SQL, MSSQL or MySQL. This tutorial should help you with accessing databases. For the purpose of this tutorial I will be demostrating examples in VB and Java. These examples have be compiled using VB5/6 and Java 1.3.1 and Access 97. SQL stands for "Structured Query Language". This language allows us to pose complex questions of a database. It also provides a means of creating databases. Many database products support SQL, this means that if learn how to use SQL you can apply this knowledge to countless other databases. SQL works with relational databases. A relational database stores data in tables (relations). A database is a collection of tables. A table consists of a list of records - each record in a table has the same structure, each has a fixed number of "fields" of a given type. SQL also has commands to create tables, to add records, to delete records and to change the value of fields of existing records; you can specify read and write permissions for other users; you can commit and roll back transactions; you can add and delete fields from existing tables, specify indexes and create views. SQL is easy to learn and because of that, with the information I provide here you will be able to add, update, retrieve and delete records in any database. Element K has two SQL self-study courses as well as two
instructor-led courses. If you have access to the self-study course I would recommend that you take a look. The SQL courses links below. SQL Fundamentals of Querying SQL Advanced Querying
Select
When querying a database you must tell the database what record(s) you want to view, add, edit or delete. You do this by using the Select statement. With "Select", you can tell the database what table you will be querying. Say we have a database that has a table named Employees and has the following records. FistName LastName Address Phone SSNumber To retrieve the Employees table all we have to do is query the database with the following statement. Select * From Employees; The wild card character (*) allows you to retrieve all the records in a table with out listing them one by one. With out the wild card the statement would look like the statement below. Select FirstName, LastName, Address, Phone, SSNumber From Employees; Lets say we only want a list of employees first and last names, the statement would look like this: Select FistName, LastName From Employees;
From
You can not have a SQL statement with out using "From", since the From clause tells the database what table you are querying. If you just typed, "Select FirstName, LastName" the database would not know where to find that information. So the "From" clause tells the database what table you are selecting your records from. So the statement below tells the database that you are selecting all the records in the Employees table.
Quick Test Using the table below use the Select From statement to retrieve the employees first and last name and SS# Employees FirstName LastName Address John Doe 123 Elm St Jane Doe 5525 Oak LN John Smith 3325 LakeView Dr Jane Smith 882 S Main
Conditional Selection
There will be times when you want to filter your queries to the database, this can be done using "Where" and "Like" and by using the "And" and "Or " operators.
Where clause
The "Where" clause is used as a filter. So if you only want to retrieve records "Where " the last name is Smith then the Select statement would look like this. Select * From Employees Where LastName = 'Smith'; As you can see we used the equal sign (= ) to tell the database the last name should equal Smith. Below is the list of Conditional selections. Also you will notice that I used single quotes around the name, This is required when querying a string. = <> or != (see manual) < > <= >= Equal Not Equal Less Than Greater Than Less Than or Equal To Greater Than or Equal To
Like
See Below
Lets say we want to retrieve a list of employees who's first name is John. Select * From Employees Where FirstName = 'John';
Like operator
The Likeoperator like the Where clause filters your request to the database. Say you only want to view a list of employees who's last name start with a "M" or end with a "S", then you would use the Like command with your Select statement. Select * From Employees Where LastName Like 'S%'; The above statement tells the database that you want a list of all employees who's last name starts with a "S". In SQL the percent(%) key is used as a wild card. So you will get a list of employees who's last name starts with a "S", no matter what precedes the "S" it could be numbers or letters. Once again it will depend on your database as to what wild card you use. If you are accessing an Access DB then the asterisk (*) would be used. Select * From Employees Where FirstName Like '%W'; The above statement tells the database that you want a list of all employees who's first name ends with a "W". Notice that the percent(%) key is now in front of the letter we want to filter. If you want to find an employee who had a "D" in there last name you would use the following statement. Select * From Employees Where LastName Like '%D%'; Other possibilities of using LIKE, or any of these discussed conditionals, are available, though it depends on what DBMS you are using; as usual, consult a manual for the available features on your system, or just to make sure that what you are trying to do is available and allowed.
And & Or
The AND operator joins two or more conditions, and displays a row only if that row's data satisfies ALL conditions listed (i.e. all conditions hold true). The OR operator joins two or more conditions, but returns a row if ANY of the conditions listed hold true.
To further discuss the SELECT statement, let's look at a new example table EmployeesStats Benefits 15000 15000 15000 12500 12000 10000 10000 7500 7500
EmployeeID 010 105 152 215 244 300 335 400 441
Salary 75000 65000 60000 60000 50000 45000 40000 32000 28000
EmpPosition Manager Manager Manager Manager Staff Staff Staff Entry-Level Entry-Level
Lets say we want a list of employees who has a salary over 40k and is part of the staff, you would use the following select statement using the And operator. SELECT * FROM EmployeesStats WHERE Salary > 40000 AND EmpPosition = 'Staff'; Lets say we want a list of employees who make less then 40k or have benefits less then 10k. We would use the select statement using the Or operator. SELECT * FROM EmployeesStats WHERE Salary < 40000 OR Benefits < 10000; You can also combine the And and Or operators to further filter your query. Lets say you want to a list of employees how are Managers and have a salary over 65k or have benefits over 12.5k. You would use the following select statement. Select * From EmployeesStats Where EmpPosition = 'Managers' And Salary > 65000 Or Benefits > 12500; First, SQL finds the rows where the salary is greater than $65,000 and the position column is equal to Manager, then taking this new list of rows, SQL then sees if any of these rows satisfies the previous AND condition or the condition that the Benefits column is greater than $12,500. Subsequently, SQL only displays this second new list of rows, keeping in
mind that anyone with Benefits over $12,500 will be included as the OR operator includes a row if either resulting condition is True. Also note that the AND operation is done first.
Quick Test Using the above Employees table what would be the results of the three(3) select statements?
Depending on how the database was designed the record can either be placed at the end of the records, as it did here. Or it can be placed at the end of the "Staff" records. The following Insert Into statement will also work. Insert Into EmployeesStats (EmployeeID, Salary, Benefits) Value (500, 35000, 10000); What you will notice, we did not add the EmpPosition. This was done to show you can add only pacific records. But once again, it would also depend on how the database was design. It could be that the database was designed not to allow null records for the EmpPosition. Meaning you must enter the EmpPosition or the database will not let you add the record. In that case the Insert Into statement would look like this: Insert Into EmployeesStats (EmployeeID, Salary, Benefits, 'EmpPosition') Value (500, 35000, 10000, 'Staff'); Deleting Data When deleting records do it with caution! Once you delete a record you can not go back and undelete it. This would be a good place to add code in your application to verify the deletion before the record is actually deleted. To delete a specific record you would use the Delete From statement. To delete the record we just created, we would use the following Delete statement. Delete From EmployeesStats WHERE EmployeeID = 500; Now assuming that the database was design so the EmployeeID would be unique, the above statement will delete Employee number 500. However you can never be too careful when deleting records, so you can be more specific.
Delete From EmployeesStats Where EmployeeID = 500 And Salary = 35000 And Benefits = 10000 And EmpPosition ='Staff' ; Now the record will not be deleted unless all the above statements are true. It requires more typing but remember if you delete a record by mistake there's not going back and recovering that record. Lets say we decided to get rid of all managers and remove them from the database, then the following Delete Statement would work. Delete From EmployeesStats Where EmpPosition = 'Manager'; Note: Omitting the Where clause will cause all EmployeesStats records to be deleted so be careful! Updating Data There will be times when you need to update a records. An example of this is when an employee receives a raise. You don't what to delete their record and add a new one just to change their salary, that wouldn't be very smart. That is where the Updating clause comes in. To update the salary of the employee we just added we would do the following. Update EmployeesStats Set Salary = 40000 Where EmployeeID = 500; You will need conditionals in order to make sure you are increasing the correct employee salary. Here we used the Where clause. Additional records can be set by separating equal statements with commas. Update EmployeesStats Set Salary = 40000, EmpPosition = 'Manager' Where EmployeeID = 500; With the above statement you are changing the employees salary and position of employee number 500. Quick Test Using the EmployeesStats table above write statement that will add an employee with the following values EmployeeID = 550 Salary = 27500 Benefits = 10000 Position = Staff
Using the EmployeesStats table write a statement that will delete employee number 010 Using the EmployeesStats table write a statement that will change employee 335 salary to 60000 and EmpPosition to Manager.
Final Notes
Learning basic SQL will allow you to work with just about any database as long as your database is ANSI (American National Standards Institute) standard. Here we only went over the very basic SQL commands, however with these commands you can add, update, delete and view any record in a database. If you think you will be working with databases in the future I would suggest that you fully learn SQL. It only takes a few hours to learn, yes it is that easy. The trick may be incorporating it with your Database, but like I stated earlier as long as your database is SQL92 compliant you shouldn't have any major problems. The only problems that might arise are the characters used in some of the statements. Example: The Like wild card search SQL uses the percent(%) Unix uses (*) or (?) Some of the clauses and functions we did not go over Distinct - Distinct is used to eliminate duplicate records. Group By - The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) Order By - ORDER BY is an optional clause which will allow you to display the results of your query in a sorted order (either ascending order or descending order) based on the columns that you specify to order by. Having - The HAVING clause allows you to specify conditions on the rows for each group Join - Joins allow you to link data from two or more tables together into a single query result - from one single SELECT statement. IN and BETWEEN Conditional Operators In - The IN conditional operator is really a set membership test operator. That is, it is used to test whether or not a value (stated before the keyword
IN) is "in" the list of values provided after the keyword IN. Between - The BETWEEN conditional operator is used to test to see whether or not a value (stated before the keyword BETWEEN) is "between" the two values stated after the keyword BETWEEN Aggregate functions MIN MAX SUM AVG COUNT COUNT(*) returns the smallest value in a given column returns the largest value in a given column returns the sum of the numeric values in a given column returns the average value of a given column returns the total number of values in a given column returns the number of rows in a table
Data Control
As stated earlier, the Data Control is the easiest way to access a Database. You add the Data Control to your project and link it to the database. This can be done by using the property window or through code. These demos will be using code. We will be using the database table below to query the database. The way this database is set up the CatNo is Primary Key and
will not allow duplicate catalog numbers, The Title, Star, CoStar and Type are all set up as strings and the rDate is set up as a Date format. Video.mdb Movies CatNo S0001 S0002 S0003 S0004 Title The Net Independence Day Jerry Maguire Miss Congeniality Star Sandra Bullock Will Smith Tom Cruise Sandra Bullock CoStar Jeremy Northam Bill Pullman Cuba Gooding, Jr Michael Caine rDate 1995 1996 1996 2000 Type A S C C
The quickest way to display records in a database is to use the DBGrid in conjunction with the Data Control. So add the DBGrid to your your application along with the Data Control and a Command button. Set the DataSource of the DBGrid to Data1(This will link the DBGrid to the database through the Data Control). Now using code we will have all the records in the database displayed in the DBGrid. Private Sub Command1_Click() Data1.DatabaseName = App.Path & "\video.mdb" 'This tells the Data control where to find the database. Data1.Connect = ";pwd=password" 'This tells the Data1 control its connecting to password protected Access Database. Data1.RecordSource = "Select * From Movie" 'This tells the Data control what table to pull the records from. Data1.Refresh 'When ever you use the data control you must use the Refresh method. End Sub What the above code will do is display all the records in the Move table in the DBGrid when you click on the command button. Lets say we only what to view the list of movie that have Sandra Bullock in them. All we have to do is use the Where clause. Add a text box to your application, this will be use to hold your query. Now use the following code. Private Sub Command1_Click() Data1.DatabaseName = App.Path & "\video.mdb" Data1.Connect = ";pwd=password" Data1.RecordSource= "Select * From Movie Where Star ='" & Text1 & "'"
Data1.Refresh End Sub Now to retrieve all the movies that star Sandra Bullock just type her First and Last name in the text box. If you want a list of movies that have stars with Tom in there name, then we would use the Where and Like clause. Private Sub Command1_Click() Data1.DatabaseName = App.Path & "\video.mdb" Data1.Connect = ";pwd=password" Data1.RecordSource= "Select * From Movie Where Star Like'*" & Text1 & "*'" Data1.Refresh End Sub Now if you type Tom in the text box all movies that have Tom as the star will be displayed. You may have noticed that I use the Connect property. I did this to show you it is possible to access a password protected database. If the database is not password protected then you would not include the Data1.Connect statement. Move methods Since not all your records will be displayed in the DBGrid, you will need to use the MoveFirst, MoveLast, MoveNext and MovePrevious methods. If you use text boxes to display records you will need this methods in order to move through the records in the database. Our database has six fields, CatNo, Title, Star, CoStar, rDate and Type so you will need six text boxes to hold the data in the database. You then must link the text boxes to the database via the Data Control, you do this by adding the Data Control to your project then select all the text boxes and in the property window select "DataSource" and select Data1 (make sure you set the visual property of the Data control to false). Next you must bind the text boxes with the each of the six database fields, this is done by selecting the first text box and typing CatNo in the "DataField" property of the text box. Do this for each of the text boxes (i.e. the second text box "Title" should be typed in the DataField property). Now put 4 command buttons and label them First, Previous, Next and Last. Your form should look like the figure below.
Private Sub Command1_Click() Data1.Recordset.MoveFirst End Sub Private Sub Command2_Click() If Not Data1.Recordset.BOF Then Data1.Recordset.MovePrevious End Sub Private Sub Command3_Click() If Not Data1.Recordset.EOF Then Data1.Recordset.MoveNext End Sub Private Sub Command4_Click() Data1.Recordset.MoveLast End Sub Private Sub Form_Load() Data1.DatabaseName = App.Path & "\video.mdb" Data1.RecordSource = "Select * From Movies" Data1.Refresh End Sub
Using the same database as the previous examples to load all the records in the database using DAO do the following. Private Sub Command1_Click() Dim db As Database Dim rs As RecordSet Dim sql As String sql = "Select * From Movies" Set db = OpenDatabase(App.Path & "\video.mdb", False, False, ";pwd=password") Set rs = db.OpenRecordSet(sql, dbOpenDynaset) Do While Not rs.EOF List1.AddItem rs("CatNo") & vbTab & rs("Title") & vbTab & rs("Star") & vbTab & rs("CoStar") & vbTab _ & rs("rDate") & vbTab & rs("Type") rs.MoveNext Loop rs.Close db.Close End Sub First we create a database and recordset object Then we declare a string to hold the SQL statement We create the SQL Statement We then assign object references to variables in this case db to the Database Object and rs to the RecordSet object. We then move through each of the records until it reaches the end of the file or last record (rs holds all the records) We then place each of the records in the appropriate position using the List box The records will be placed one row at a time, this will be done until all records have been added to the list box. We then close the RecordSet and Database.
That's it, the above code will display all the records in the Movies table to the List box
Open Statements
OpenDatabase The OpenDatabase method syntax has these parts The Database Object - In this case db (remember we set the Database object to db). WorkSpace - This is optional if you did not include a workspace OpenDatabase use the default workspace. dbName - This is the name and location of the Database or the the data source name (DSN). Options - Optional. A Variant that sets various options for the database, as specified in Settings. Read-Only - Optional. Set True if you want to open the Database as read only False if you want read/write access. Connect - Optional. Specifies various connection information, including passwords. This can be use to connect to any ODBC compliant database. OpenRecordSet The OpenRecordset method syntax has these parts RecordSet - An object variable that represents the Recordset object you want to open Object - An object variable that represents an existing object from which you want to create the new Recordset Source - A String specifying the source of the records for the new Recordset. The source can be a table name, a query name, or an SQL statement that returns records. For table-type Recordset objects in Microsoft Jet databases, the source can only be a table name. Type * - Optional. A constant that indicates the type of Recordset to open. You can use one of the following constants. dbOpenTable - Opens a table-type Recordset object (Microsoft Jet workspaces only). dbOpenDynamic - Opens a dynamic-type Recordset object, which is similar to an ODBC dynamic cursor. (ODBCDirect workspaces only) dbOpenDynaset - Opens a dynaset-type Recordset object, which is similar to an ODBC keyset cursor. dbOpenSnapshot - Opens a snapshot-type Recordset object, which is similar to an ODBC static cursor.
dbOpenForwardOnly - Opens a forward-only-type Recordset object *Note If you open a Recordset and you don't specify a type, OpenRecordset creates a table- type Recordset, if possible. If you specify a linked table or query, OpenRecordset creates a dynaset- type RecordSet. Since I used a query in my statement I could have omitted the "dbOpenDynaset" and OpenRecordset would have used it by default. **Options - Optional. A combination of constants that specify characteristics of the new Recordset. You can use a combination of the following constants. dbAppendOnly - Allows users to append new records to the Recordset, but prevents them from editing or deleting existing records (Microsoft Jet dynaset-type Recordset only). dbSQLPassThrough - Passes an SQL statement to a Microsoft Jet-connected ODBC data source for processing (Microsoft Jet snapshot-type Recordset only). dbSeeChanges - Generates a run-time error if one user is changing data that another user is editing (Microsoft Jet dynaset-type Recordset only). This is useful in applications where multiple users have simultaneous read/write access to the same data. dbDenyWrite - Prevents other users from modifying or adding records (Microsoft Jet Recordset objects only). dbDenyRead - Prevents other users from reading data in a table (Microsoft Jet table-type Recordset only). dbRunAsync - Runs an asynchronous query (ODBCDirect workspaces only). dbExecDirect - Runs a query by skipping SQLPrepare and directly calling SQLExecDirect (ODBCDirect workspaces only). Use this option only when you're not opening a Recordset based on a parameter query. For more information, see the "Microsoft ODBC 3.0 Programmer's Reference." dbInconsistent - Allows inconsistent updates (Microsoft Jet dynaset-type and snapshot-type Recordset objects only). dbConsistent - Allows only consistent updates (Microsoft Jet dynaset-type and snapshot-type Recordset objects only). **Note The constants dbConsistent and dbInconsistent are
mutually exclusive, and using both causes an error. Supplying a lockedits argument when options uses the dbReadOnly constant also causes an error. Lockedits - Optional. A constant that determines the locking for the Recordset. You can use the following constants. dbReadOnly - Prevents users from making changes to the Recordset (default for ODBCDirect workspaces). You can use dbReadOnly in either the options argument or the lockedits argument, but not both. If you use it for both arguments, a run-time error occurs. dbPessimistic - Uses pessimistic locking to determine how changes are made to the Recordset in a multi-user environment. The page containing the record you're editing is locked as soon as you use the Edit method (default for Microsoft Jet workspaces). dbOptimistic - Uses optimistic locking to determine how changes are made to the Recordset in a multi-user environment. The page containing the record is not locked until the Update method is executed. dbOptimisticValue - Uses optimistic concurrency based on row values (ODBCDirect workspaces only). dbOptimisticBatch - Enables batch optimistic updating (ODBCDirect workspaces only). I know this may look a little daunting but its not. Actually you'll find that most of your statements will use the default values. I would say that 98 % of my access statements look like this: Private Sub Command1_Click() Dim db As Database Dim rs As RecordSet Dim sql As String sql = "Select * Statement" Set db = OpenDatabase(App.Path & "\dbname.mdb", False, False, ";pwd=password") Set rs = db.OpenRecordSet(sql)
More DAO
The reset of our examples using DAO will be adding, deleting and editing records. We will add 7 Text boxes, 1 List box and two Command buttons.
We will use these to add records and search for records in the database. The search box will look up the star of the movie. The form should look like this.
Code to Add records Private Sub Command1_Click() Dim db As Database Dim rs As RecordSet Set db = OpenDatabase(App.Path & "\video.mdb", False, False, ";pwd=password") Set rs = db.OpenRecordSet("Movies") rs.AddNew rs("CatNo") = txtCatNo rs("Title") = txtTitle rs("Star") = txtStar rs("CoStar") = txtCoStar rs("rDate") = txtDate rs("Type") = txtType rs.Update rs.Close db.Close End Sub Code to Search records Private Sub Command2_Click() Dim db As Database Dim rs As RecordSet Dim sql As String
List1.clear sql = "Select * From Movies Where Star =' " & txtSchStar & " ' " Set db = OpenDatabase(App.Path & "\video.mdb", False, False, ";pwd=password") Set rs = db.OpenRecordSet(sql) Do While Not rs.EOF List1.AddItem rs("CatNo") & vbTab & rs("Title") & vbTab & rs("Star") & vbTab & rs("CoStar") & vbTab _ & rs("rDate") & vbTab & rs("Type") rs.MoveNext Loop rs.Close db.Close End Sub Once again we create a Database and Recordset object and since we will be querying the database we declare a string to hold the query (sql). Since you can search more then once you want to clear the List box for each search so I called the (List1.clear). When the command button is clicked the database will look for the Star that is typed in the txtSchStar text box. It will then display the results in the list box. The vbTab will put a tab between each record. By using the vbTab I can line up each of the columns using the TabStops Function below. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Public Const LB_SETTABSTOPS = &H192 Private Function TabStops() 'Set up tab stops in the list box ReDim TabStop(1 To 5) As Long 'Set the tab stop points. TabStop(1) = 40 TabStop(2) = 140 TabStop(3) = 210 TabStop(4) = 280 TabStop(5) = 310
'Send LB_SETTABSTOPS message to ListBox. Call SendMessage(List1.hwnd, LB_SETTABSTOPS,5, TabStop(1)) 'Refresh the ListBox control. List1.Refresh End Sub Now type TabStops under Form_Load, when you do a search your List box display will go from this to this. Code to Delete records Private Sub mnuDelete_Click() Dim db As Database Dim sql, dCatno As String Dim noAns As Integer dCatno = InputBox(Please enter the the Catalog number you wish to delete") noAns = MsgBox("Are you sure you want to delete this record?, vbYesNo) If noAns = 7 Then MsgBox "Delete has been cancelled":Exit Sub sql = "Delete * From Movies Where CatNo='" &dCatno &"'" Set db = OpenDatabase(App.Path & "\video.mdb", False, False, ";pwd=password") db.Execute sql MsgBox "Record has been deleted" db.Close End Sub Here we used the inputbox to get the catalog number that you want to delete. Since you cant undo a delete we add code to make sure you want that record deleted. If the user changes there mind clicking the "No" button will cancel the delete by exiting the sub procedure. The vbYesNo button can produce 1 of 2 integers 6 = Yes and 7 = No, if the user confirms the deletion they will press the "Yes" button which will produce a 6 and the record will be deleted. We then create the SQL statement to delete the record, we delete the record that is input in the InputBox. Then if "Yes" is clicked we Execute the sql statement to delete the record, then we confirm the deletion. Code to Edit records Command3_Click() Dim db As Database Dim rs As RecordSet Set db = OpenDatabase(App.Path & "\video.mdb", False, False,
";pwd=password") Set rs = db.OpenRecordSet("Movies") rs.Edit rs("CatNo") = txtCatNo rs("Title") = txtTitle rs("Star") = txtStar rs("CoStar") = txtCoStar rs("rDate") = txtDate rs("Type") = txtType rs.Update rs.Close db.Close End Sub This code assumes that you have already loaded the record you wish to change in the textbox. This code looks just like the code you use to add to the database but, "Edit" is used instead of AddNew.
Final Thoughts
DAO is very easy to use and is great for working with Access and other ISAM(Indexed Sequential Access Method) file types. ISAM is a file management system developed at IBM that allows records to be accessed either sequentially (in the order they were entered) or randomly (with an index).
What is ADO
ADO which stands for ActiveX Data Objects is a Microsoft technology that is a programming interface to access databases. ADO was designed to be a high-level interface to provide ease of access to data stored in a wide variety of database sources. The earlier versions of ADO could only access relational databases with fixed columns and data types. However, since the release of version 2.5, ADO is now able to interface not only with relational databases, but also with non-relational databases, folders, data files, and even e-mail messages. For example, ADO can now handle data that are contained in a tree-like structure with a root, nodes, and leaves. It can also handle data where the number of columns and the data type vary from row to row. This represents a significant improvement in the usefulness and value of ADO.
ADO is part of Microsoft Data Access Components (MDAC) and can be downloaded here for free. The latest version of MDAC is 2.6. ADO can be used with a variety of programming languages, including Visual Basic, VBScript, JScript, Visual C++, and Visual J++. Further, by using ASP, you can reference ADO components on HTML-generated Web pages.
"Provider=MSIDXS;" OLE DB Provider for Internet Publishing: "Provider=MSDAIPP.DSO; Data Source=http://www.websitename.com/" OLE DB Provider for Microsoft Jet: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=dbName.mdb;" OLE DB Provider for ODBC Databases: "Provider=MSDASQL; Driver={SQL Server}; Server=DBServer; DataBase=GuruDatabase;" OLE DB Provider for Oracle: "Provider=MSDAORA; Data Source=SourceTable;" OLE DB Provider for SQL Server: "Provider=SQLOLEDB; Data Source=SourceName; Network Library=DBMSSOCN; Initial Catalog=GuruPubs;" The Provider property is used to set or return the name of the provider for a specific Connection object. The default is MSDASQL (Microsoft OLE DB provider for ODBC).
Provider Code ADSDSOObject Microsoft.Jet.OLEDB.4.0 MSDAIPP.DSO.1 MSDAORA MSDAOSP MSDASQL MSDataShape MSPersist SQLOLEDB
Provider Active Directory Services Microsoft Jet databases Microsoft Internet Publishing Oracle databases Simple text files Microsoft OLE DB provider for ODBC Microsoft Data Shape Locally saved files Microsoft SQL Server
dbConnect.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=dbName.mdb;" dbConnect.ConnectionTimeout = 0 dbConnect.Open You can also use Driver in place of Provider Dim Conn1 As New ADODB.Connection Dim dbConn As String dbConn = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=nwind.mdb;" & _ "DefaultDir=C:\vb;" & _ "Uid=Admin;Pwd=;" dbConn = "Driver={SQL Server};" & _ "Server=MyServerName;" & _ "Database=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword;" dbConn = "Driver={Microsoft ODBC for Oracle};" & _ "Server=OracleServer.world;" & _ "Uid=myUsername;" & _ "Pwd=myPassword;" dbConn = "Driver={mySQL};" & _ "Server=db1.database.com;" & _ "Port=3306;" & _ "Option=131072;" & _ "Stmt=;" & _ "Database=mydb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword;" dbConn = "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _ "Dbq=c:\somepath\;" & _ "Extensions=asc,csv,tab,txt;" & _ "Persist Security Info=False" Open Method The Open method is called on a Recordset object to open a cursor which gives you access to the records contained in the base table, the results from a query, or a previously saved Recordset.
There are five optional parameters: Source - Optional can be one of the following,Command object, SQL query string, table name, stored procedure call, URL, full or relative path/file name,Stream object containing a Recordset ActiveConnection - Optional parameter is either a connection string that defines the connection, or it is a variant that contains the valid Connection object associated with the Recordset CursorType - Optional is one of the CursorTypeEnum constants that specifies the type of cursor to use when you open a Recordset object.
Constant Value Description A dynamic cursor with both forward and backward scrolling where additions, deletions, insertions, and updates made by other users are visible Default, a forward scrolling only, static cursor where changes made by other users are not visible A keyset cursor allows you to see dynamic changes to a specific group of records but you cannot see new records added by other users A static cursor allowing forward and backward scrolling of a fixed, unchangeable set of records Cursor type not specified
adOpenDynamic
adOpenForwardOnly
adOpenKeyset
adOpenStatic adOpenUnspecified
3 -1
LockType - Optional is one of the LockTypeEnum constants that indicates the type
of lock in effect on a Recordset. The default is adLockReadOnly. LockTypeEnum Constants Constant adLockBatchOptimistic Value 4 Description Multiple users can modify the data and the changes are cached until BatchUpdate is called Multiple users can modify the data which is not locked until Update is called The provider locks each record before and after you edit, and prevents other users from modifying the data Read-only data Lock type unknown
2 1 -1
Options - Optional tells the provider how to evaluate the Source parameter when it
contains something other than a Command object. The appropriate use of this option can
speed up performance since ADO will not have to determine the type of the data source. It can be one or more of the following CommandTypeEnum or ExecuteOptionEnum constants. CommandTypeEnum Constants Constant adCmdFile adCmdStoredProc adCmdTable adCmdTableDirect adCmdText adCmdUnknown adCmdUnspecified Value 256 4 2 512 1 8 -1 Description Evaluate as a previously persisted file Evaluate as a stored procedure Have the provider generate an SQL query and return all rows from the specified table Return all rows from the specified table Evaluate as a textual definition The type of the CommandText parameter is unknown Default, does not specify how to evaluate
ExecuteOptionEnum Constants
Constant adAsyncFetch adAsyncFetchNonBlocking Value 32 64 Description Records are fetched asynchronously Records are fetched asynchronously without blocking the return
Once again this may be a little daunting but remember most of the time you will use the default parameters. Now to open any of the above databases you would use the Open method. conn1.Open dbConn
Viewing Records
We will be going over the code that will allow us to view, add, edit and delete records using the RecordSet.
RecordSet Properties The following is a list of the properties available for a RecordSet, with a brief description of each: AbsolutePage AbsolutePosition ActiveConnection BOF Bookmark CacheSize CursorLocation CursorType EOF EditMode Filter LockType MaxRecords PageCount PageSize RecordCount Source Status RecordSet Methods < of description brief a with object, RecordSet the for available methods list is following> AddNew CancelBatch CancelUpdate Clone Close Delete GetRows Move MoveNext MovePrevious MoveFirst MoveLast NextRecordSet Add a new record to the RecordSet Cancel pending batch updates Cancel pending update Copy the RecordSet Close the RecordSet Delete current record Retrieve multiple records Move the record pointer to a specific record Move the record pointer to the next record Move the record pointer to the previous record Move the record pointer to the first record move the record pointer to the last record Load the next RecordSet in a multi-set query Page of current position Current position Active Connection Object Beginning of File Bookmark of current position Number of records cached Server or Client Forward, static, dynamic, keyset End of File Whether or not an edit is in progress What kind of records to hide Record lock type for edits or updates Maximum number of records to retrieve Total number of pages Number of records per page Total number of records Source Command Object Status of last action
Open the RecordSet (execute the query) Re-execute the last query executed Synchronize the data with the server Determine if a feature is supported by provider Update the current record Update pending batched record updates
Once we connect to the Database we can now make queries. Using the video.mdb database we can get a list of all the records in the Movies table using the following code. Since I'm using a Access database we will use the Access Driver. Dim Conn1 As New ADODB.Connection Dim rs As New ADODB.Recordset Dim AccConn As String AccConn = "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=video.mdb;" & _ "DefaultDir=" & App.Path& ";" & _ "Uid=;Pwd=;" Conn1.Open AccessConnect Set rs = Conn1.Execute("SELECT * FROM Movies") Do While Not rs.EOF List1.AddItem rs(0) & vbTab & rs(1) & vbTab & rs(2) & vbTab & rs(3) & vbTab & rs(4) rs.MoveNext Loop rs.Close Conn1.Close Noticed that I didn't add the record name in the recordset but the number. This can come in handy when you have an array of text boxes you want to load the records in. Like an array the database columns start at zero(0). So rs(0) = rs("CatNo").
Adding Records
This code will allow you to add records to the video.mdb database using AddNew. Private Sub cmdAdd_Click() Dim cn As ADODB.Connection Dim rs As ADODB.Recordset
Dim Con, sql As String Dim i As Integer Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;" sql = "Select * From Movies" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic rs.AddNew For i = 0 To 5 rs(i) = Text1(i) Next i rs.Update rs.Close cn.Close 'Clear text boxes For i = 0 To 5 Text(i) = "" Next i End Sub Version 2 for adding records to the database using SQL's Insert Into. Private Sub cmdAdd2_Click() Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim Con, sql As String Dim i As Integer Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;" sql = "INSERT INTO Movies Values" _ & "('" & Text1(0) & "','" & Text1(1) & "','" & Text1(2) & "','" & Text1(3) & "','" & Text1(4) & "','" & Text1(5) & "')" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset
cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic Set rs = Nothing cn.Close 'clear text boxes For i = 0 To 5 Text1(i) = "" Next i End Sub Lets go over the above code, first we create the Connection and Recordset object. We then declare 2 strings, one to hold the database connection and the other to hold the recordset string. We also declared an integer, this will be used to clear the text boxes once the records are added to the database. (Here is where that textbox array comes in.) We then create the Connection string, this string will tell what driver we will be using to connect, the name of the database, the user name and password if any. Since we did not have a user name and password attached to our database this parameters are left blank. We then create the SQL statement that will add the records to the database. This is done by using the Insert Into SQL statement. Now that we have everything declared and set, we then open the database and recordset connection, then we call the SQL Insert Into statement that will take the contents of the text boxes and add them to the database. We then clear the recordset and close the database and clear all the text boxes. As you can see both methods will add the records to the database, the difference, is the second one can be ported to other databases besides Access. All we have to do is change the Driver or Provider and we can access a Oracle, MS SQL, MySql or any other ODBC compliant database.
Deleting Records
At some point and time your database may become filled with out dated records, who's only purpose is to take up space. When this happens you will need to delete the old records to make space for new ones. This is done by using the Delete statement. Don't forget that when you use the Delete statement that you need a Where statement (remember you don't want to delete all your records by mistake!).
Private Sub cmdDelete_Click() ' Delete a record and clear the textboxes Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim Con, sql As String Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;" sql = "Select * FROM Movies WHERE CatNo ='" & txtCatNo & "'" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic rs.Delete rs.Close cn.Close 'Clear text box txtCatNo = "" The SQL version of the Delete statement Private Sub cmdDelete_Click() Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim Con, sql As String Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;" sql = "Delete FROM Movies WHERE CatNo ='" & txtCatNo & "'" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic Set rs = Nothing cn.Close 'Clear text box txtCatNo = "" End Sub
Updating Records
This code will allow you to update an existing record. Private Sub cmdEdit_Click() Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim Con, sql As String Dim i As Integer Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;" sql = "Select * From Movies Where CatNo='" & txtCatNo & "'" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic For i = 0 To 5 rs(i).Value = Text1(i) Next i rs.Update 'Clear text box For i = 0 To 5 Text1(i) = "" Next i txtEdit = "" Set rs = Nothing cn.Close End Sub Here is the SQL version of the Update method Private Sub cmdEdit_Click() Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim Con, sql As String Dim i As Integer Con = "Driver={Microsoft Access Driver (*.mdb)};" & _ "DBQ=video.mdb;" & _ "DefaultDir=" & App.Path & ";" & _ "Uid=;Pwd=;"
sql = "Update Movies Set CatNo='" & Text1(0) & "', Title='" _ & Text1(1) & "', Star='" & Text1(2) & "', CoStar='" & Text1(3) & _ "', rDate='" & Text1(4) & "', Type='" & Text1(5) & "' Where Title='" & txtTitle & "'" Set cn = New ADODB.Connection Set rs = New ADODB.Recordset cn.Open Con rs.Open sql, cn, adOpenDynamic, adLockOptimistic 'Now clear the text boxes For i = 0 To 5 Text1(i) = "" Next i Set rs = Nothing cn.Close End Sub Now lets go over the code to update the database. As always we create and set the database and recordset objects. We then declare the string variables to hold the connection and recordset strings, and the integer to clear the text boxes. We then call the sql statement, in the first example it will hold all the records of the specified CatNo and then update them using the Value property and the Update method. In the second example the Update Set statement will update the records that are in the text boxes. We then clear all the text boxes and close the database.
Summery
As you can see Microsoft has made it easy to work with databases using VB. At is basic level we can use the Data Control to view and manipulate records in the database. As the complexity of your application grows so can your tools to work with databases. DAO is good for small application, like the video catalog program, it is quick and efficient. But the more complex your applications, such as Client/Server or Web development then ADO comes in to play. Weather you are just starting out or a seasoned VB programmer, there are tools available to you to access and manipulate databases.
Retrieving Records
To retrieve records using Java you must create a ResultSet and Statement object . The ResultSet object will hold the Selection string and the Statement will then execute the the ResultSet. //Select Query.java: Query an MS Access database using JDBC. Retrieve all records import java.sql.*; class SelectQuery { public static void main (String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:video"; Connection conn = DriverManager.getConnection(url,"",""); Statement stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT * FROM Movies"); while ( rs.next() ) { String CatNo = rs.getString("CatNo"); String Title = rs.getString("Title"); String Star = rs.getString("Star"); String CoStar = rs.getString("CoStar"); String rDate = rs.getString("rDate"); String Type = rs.getString("Type"); System.out.println(CatNo + " " + Title + " " + Star + " " + CoStar + " " + rDate + " " + Type); } rs.close(); conn.close(); } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); }
} } Retrieve a single record import java.sql.*; class SelectOneQuery { public static void main (String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:video"; Connection conn = DriverManager.getConnection(url,"",""); Statement stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT * FROM Movies Where CatNo='S0010'"); while ( rs.next() ) { String CatNo = rs.getString("CatNo"); String Title = rs.getString("Title"); String Star = rs.getString("Star"); String CoStar = rs.getString("CoStar"); String rDate = rs.getString("rDate"); String Type = rs.getString("Type"); System.out.println(CatNo + " " + Title + " " + Star + " " + CoStar + " " + rDate + " " + Type); } rs.close(); conn.close(); } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } } } Depending on which Select Statement you use you can retrieve one or all the records in the database. As you can see the select statement is the same as DAO and ADO.
You can use the same code to open a Oracle database base or any database by just changing the JDBC driver. The code below will open a Oracle database. class SelectQuery { public static void main (String[] args) { try { Class.forName(oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:video"; Connection conn = DriverManager.getConnection(url,"",""); Statement stmt = conn.createStatement(); ResultSet rs; As you can see this make porting your application to other database sources very easy.
conn.close(); System.out.println("Item had been Added"); } catch (Exception e){ e.printStackTrace(); } } } Updating records import java.sql.*; class UpdateQuery { public static void main (String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:video"; Connection conn = DriverManager.getConnection(url,"",""); String sql = "Update Movies Set CatNo ='S0098' Where CatNo='S0099'"; Statement stmt = conn.createStatement(); int rows = stmt.executeUpdate(sql); conn.commit(); stmt.close(); conn.close(); System.out.println("Item had been updated"); } catch (Exception e){ e.printStackTrace(); } } } Deleting records import java.sql.*; class DeleteQuery { public static void main (String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:video"; Connection conn = DriverManager.getConnection(url,"",""); String sql = "Delete From Movies Where CatNo='S0098'"; Statement stmt = conn.createStatement(); int rows = stmt.executeUpdate(sql); conn.commit(); stmt.close(); conn.close(); System.out.println("Item had been deleted"); } catch (Exception e){ e.printStackTrace(); } } } Have you noticed the only things I had to change in each of the source code? The SQL statement (String sql ), and the println (Print Line) string.
Summary
As you can see it's easy to work with databases using Java. If you have not taken the time to check out, "The Java Tutorial". Now is the time to do so, Sun has made this tutorial available for free, you can view it on line or download the full tutorial. They do have a section on JDBC Database Access. I have only touched on the very basics of accessing and manipulating databases using Java. Take a look at the links below to further delve in to accessing databases using Java. Sun's Java Tutorial Getting Started with the JDBC API
Resources
Microsoft ADO Microsoft ADO FAQ ADO FAQ ADO and DAO examples VB Database tips Java JDBC Tips
Books Visual Basic Serious ADO: Universal Data Access with Visual Basic by Robert MacDonald ADO Examples and Best Practices by William R. Vaughn Visual Basic Developer's Guide to ADO by Mike Gunderloy DAO Object Model: The Definitive Guide by Helen Feddema Java Database Programming with JDBC and Java, 2nd Edition by George Reese JDBC(TM) API Tutorial and Reference: Universal Data Access for the Java 2(TM) Platform (The Java(TM) Series) by Seth White, Maydene Fisher, Rick Cattell, Graham Hamilton, Mark Hapner Understanding SQL and Java Together : A Guide to SQLJ, JDBC, and Related Technologies by Jim Melton
In Conclusion
It doesn't matter if your language of choice is VB or Java, Sun and Microsoft has made it easier then ever to access and manipulate databases. And with scores of resources on the net, you are only a click away from getting information, tips and help on working with databases. Good luck and have fun!
2001 Marietta Crockett Disclaimer