You are on page 1of 44

ADO With MSVB Express: Introduction Introduction to Databases A database is a list or a group of lists of objects organized to make the

list(s) and its (their) values easy to create and manage. In the computer world, this suggests, rightly, that the list(s) and its(their) values are stored in a machine. As information becomes of high importance, almost every company keeps some type of database, whether it includes its employees, its customers, or the products it sells. Microsoft JET To make it possible to create computer databases, throughout its history, Microsoft developed various libraries and programming environments. Microsoft JET is a library used to create and manage Microsoft Access types of databases using a language or a programming environment of your choice. This means that the library can be used from either Microsoft Access, another Microsoft development studio, or an environment from another company. To make this possible, you must first obtain the library. In most cases, you should have this library already installed in your computer. If not, it is freely available by downloading from the Microsoft web site. Once there, simply do a search on "Microsoft JET". After downloading it, install it. Microsoft ActiveX Data Objects or ADO, is a library used to manage databases. To make it possible, it uses the driver that is part of Microsoft JET. Microsoft ActiveX Data Object Extensions for Data Definition Language and Security abbreviated ADOX, is an addition to ADO. It can be used to create and manage a database, providing some of the same operations as ADO but also some operations not possible in ADO. Microsoft Visual Basic Express Any computer language or programming environment that wants to use Microsoft JET provides its own means of accessing the library. In fact, it is not usual to manually write code that takes advantage of Microsoft JET. This is usually how some programmers would create and manage a web database (through Active Server Pages (ASP)). Still, in most cases, and depending on the language you decide to use to create and manage your database, you would need either only an interpreter (which is the case if you plan to use VBScript, JavaScript, or another interpreted language) or a compiler. With the release of Microsoft Visual Studio 2005, Microsoft provided a series of free programming environments. You can use one of these to create and manage your databases. In our lessons, we will use Microsoft Visual Basic Express. You can download it free from the Microsoft web site. Once there, do a search on Visual Basic Express. Referencing a Library in a .NET Framework Based on its flexibility, you can use the .NET Framework to create and manage Microsoft JET databases. The .NET Framework is a group of many libraries under one name. When creating a project, you choose what libraries you would use, based on your goal, to perform the necessary tasks.

If you compile your project at the Command Prompt, you must call each needed library by referring to it. If you are using a visual environment, you can "visually" reference the library. In the Microsoft Visual Basic Express studio, to reference a library, you can right-click the project in the Solution Explorer -> Add -> Add Reference... You would then need to locate the library, click it, and click OK.

Database Creation Microsoft ADO Ext. Introduction To get a database, you can either use one that exists already or you can create your own. ADO by itself doesn't provide the means to create a database. To create one, you can use the Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security, abbreviated ADOX. Before using ADOX, you must reference it in your Microsoft Visual Basic project. To do this, in the Microsoft Visual Basic Express studio, you can right-click the project in the Solution Explorer -> Add -> Add Reference... In the COM tab of the Add Reference dialog box, locate the Microsoft ADO Ext. 2.7 or 2.8 for DDL and Security:

After referencing the library, you can use its classes. The classes of the ADOX library are stored in a namespace named ADOX.

The Catalog Class To create and manage various objects of a database, the ADOX namespace provides a class named Catalog. You can also use a class named CatalogClass. To use this class, you can first declare a variable of its type. Here is an example:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click ' Using the CatalogClass class of the ADOX namespace Dim catADOX As ADOX.CatalogClass End Sub

After declaring the class, you can initialize it using the New operator:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click Dim catADOX As ADOX.CatalogClass

catADOX = New ADOX.CatalogClass End Sub

Database Creation The Connection String of the Catalog To support database creation, the Catalog class is equipped with the Create() method. Its syntax is:
Create(ConnectionString As String)

The Create() method takes one argument usually referred to as the connection string. This string is made of sections separated by semi-colons. The formula used by these sections is:
Key1=Value1;Key2=Value2;Key_n=Value_n;

The first part of the connection string is called the provider. It is software that handles the database. To specify it, assign the desired name to the provider key. Here is an example:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click ' Using the Catalog class of the ADOX namespace

Dim catADOX As ADOX.Catalog = New ADOX.Catalog

catADOX.Create("Provider=" End Sub

There are various providers in the database industry. One of them is Microsoft SQL Server and it is represented by SQLOLEDB. If you want to create a Microsoft SQL Server database, specify this provider. Here is an example:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click ' Using the Catalog class of the ADOX namespace Dim catADOX As ADOX.Catalog = New ADOX.Catalog

catADOX.Create("Provider=SQLOEDB" End Sub

When creating this type of database, there are some other pieces of information you must provide in the connection string. Another provider is the Microsoft JET database engine represented as Microsoft.JET.OLEDB.4.0. To create a database for it, specify its provider accordingly. Here is an example:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click ' Using the Catalog class of the ADOX namespace Dim catADOX As ADOX.Catalog = New ADOX.Catalog

catADOX.Create("Provider=Microsoft.Jet.OLEDB.4.0" End Sub

You can also include the name of the provider as its own string. To do that, you can include it in single-quotes:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click ' Using the Catalog class of the ADOX namespace Dim catADOX As ADOX.Catalog = New ADOX.Catalog

catADOX.Create("Provider='Microsoft.Jet.OLEDB.4.0'" End Sub

If you are creating a database, the second part of the connection string can be used to specify the path and the name of the database. This section must start with the Data Source key and assigned the path that consists of the drive and the folder(s). After the last folder, the name of the database must have the .mdb extension. For example, to create a database called Exercise that would reside in a folder called Exercises of the C: drive, you can specify the connection string as follows:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateDatabase.Click Dim catADOX As ADOX.Catalog

catADOX = New ADOX.Catalog catADOX.Create("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\Exercises\Exercise.mdb") End Sub

You can also include the value of the Data Source key in single-quotes. Instead of directly passing a string to the Create() method, you can first declare a String variable, initialize it with the necessary provider/data source, and then pass that string variable to the Create() method. ADO Fundamentals Microsoft ActiveX Data Objects ADO With MSVB Express The .NET Framework is a library, developed by Microsoft, that can be used to create different types of applications, including databases, using a low-level common language that is translated from a known, and somewhat easier or regular language such as Microsoft Visual Basic. The .NET Framework comes with a technique of creating and managing databases known ADO.NET. Although ADO is a true library, ADO.NET is not a library: it is only a technique of dealing with databases. The ADO part suggests that it uses concepts similar to the ADO approach of solving database operations. The .NET part of the name means that it uses the .NET Framework. Using ADO in the .NET Framework

If you want to create an ADO database application in Microsoft Visual Basic, the .NET Framework provides a namespace named ADODB that is equipped with various classes. To access the ADODB namespace if your project, you can first create a reference to its library. To do this, in the Solution Explorer, right-click the name of the project and click Add Reference... In the COM tab of the Add Reference dialog box, locate the Microsoft ActiveX Data Objects version Library

Click OK. In the .NET Framework, ADO is represented by the ADODB namespace. The classes used to create and manage tables are stored in the ADODB namespace. The Data Source of an Application Introduction A database is a project that holds one or more lists of items. There can be other issues involved such as how the data would be made available to the users, what computer(s) would access the data, what types of users would access the database. The database could reside in one computer and used by one person. A database can also be stored in one computer but accessed by different computers in a network. Another database can be created and stored in a server to be accessed through the Internet. These and other related scenarios should be dealt with to create and distribute the database. A Data Source You may plan to create a database that would be used by one person using one computer. As your job becomes more effective, you could be asked to create another database that would be accessed by different people. Regardless of why and how, after creating a database, you should have a way of

making it available to those who would use it. To do this, you can create a data source. A database is created as a computer file and it has a path, that is, where the database file is located. The path to a file is also known as its location. The path to a database, including its name, is also called the data source. In some of your database operations, you will be asked to provide a data source for your database. In this case, provide the complete path followed by the name of the database. If you plan to access your database from another programming environment, then you should create an ODBC data source. To do this, in the Control Panel or the Administrative Tools, double-click Data Source (ODBC) to open the ODBC Data Source Administrator:

To proceed, click the Add button. This would launch a wizard. In the first page of the Create New Data Source wizard, click Microsoft Access Driver (*.mdb):

Click Finish. In the following screen, you would be asked to enter a name for the data source. You can enter the name in one or more words. The name would be used by the applications that need to access the database. This means that you should pay attention to the name you give. In the Description text box, you can enter a short sentence anyway you like. To specify the database that would be used, click Select and select an mdb database. Here is an example:

After selecting the necessary database, if you need to be authenticated in order to use the database (if the database is protected), click the Advanced button. By default, a database is meant to allow anybody to use it. In this case, you can leave the Login Name and the Password empty. Otherwise, type the necessary credentials:

After using the Set Advanced Options dialog box, click OK (or Cancel to keep it the way it previously was).

After entering the necessary information and selecting the desired database, you can click OK twice.

The Connection to a Database Introduction To use or access a database, a user typically launches it and opens the necessary object(s) from it. You too will need to access a database but with code. To programmatically access a database using the ADO library, you must first establish a connection. To support this, the ADODB namespace provides a class named Connection. You can also use ConnectionClass. To create a connection to a database, declare a variable of type ADODB.Connection or ADODB.ConnectionClass and initialize it using the New operator. This would be done as follows:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection conADO = New ADODB.Connection End Sub

Opening a Connection After declaring and initializing the Connection object, you can then open the connection. To support this, the Connection class is equipped with a method named Open. The syntax of the Connection.Open method is:
Open([ConnectionString As String = ""], [UserID As String = "", [Password As String = "", [Options As Integer = -1]

This method takes four arguments and all of them are optional. In reality, the first argument must be defined in order to establish as connection. The Connection String When establishing a connection to a database, you have two alternatives, you can use the first argument to the Connection.Open() method or you can separately create a connection string. The connection string is text made of various sections separated by semi-colons. Each section is made of a Key=Value expression. Based on this, a connection string uses the following formula:
Key1=Value1;Key2=Value2;Key_n=Value_n;

One of the expressions you can specify in the connection string is the name of the provider. To do this, type Provider= followed by the provider you are using. For most databases we will create or use here,

the provider will be Microsoft.JET.OLEDB.4.0. This means that our connection string can start with:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection Dim strConnection As String

conADO = New ADODB.Connection strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" . . .

End Sub

You can also include the value of the provider in single-quotes to delimit it. If you were working on an MSDE or a Microsoft SQL Server database, the provider would be SQLOLEDB. The second part of the connection string specifies the data source. To provide this information, you can assign the path and name of the database to the Data Source attribute. Here is an example:
Provider='Microsoft.JET.OLEDB.4.0';Data Source='C:\Programs\Example1.mdb';"

It is important to note that the content of the connection string differs from one provider to another. If you were working on a Microsoft SQL Server database, your connection string would be different from the above done for a Microsoft JET database. You can pass this connection string as the first (and probably the only) argument to the method. Here is an example:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection

conADO = New ADODB.Connection conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'") End Sub

As mentioned earlier, the first argument is optional but you must find a way to specify it. In effect, there is an alternative. To separately support the connection string as its own object, the Connection

class is equipped with a property named ConnectionString, which is of type String. To use it, declare a String variable, assign the connection string to that variable, and assign that variable to the Connection.ConnectionString property. You must do this prior to calling the Open() method. Here is an example:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection Dim strConnection As String

conADO = New ADODB.Connection strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'"

conADO.ConnectionString = strConnection conADO.Open() End Sub

The Login Credentials When creating your database, if you are working in a secure environment and the database requires authentication, you may need to provide login credentials, which include a username and a password. Normally, these properties are mostly applied if you are working on a Microsoft SQL Server database. To specify the login credentials when accessing the database, you can pass the second and the third arguments to the Open() method of the Connection class. Executing a SQL Statement After creating a connection to a database, you can specify what you want to do on the database. One of the most usual operations you can perform is to submit a SQL statement to it (the connection). This is also equivalent to executing the statement. To execute a statement, the Connection class is equipped with the Execute() method. Its syntax is:
Execute(CommandText As String, [ByRef RecordsAffected As Object, [Options As Integer = -1]) As ADODB.Recordset

The first argument, CommandText, can be a SQL statement. We will study SQL in future lessons. The second and the third arguments are optional. Here is an example:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection Dim strConnection As String Dim strStatement As String

conADO = New ADODB.Connection strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'" strStatement = "Blah Blah Blah"

conADO.Open(strConnection) conADO.Execute(strStatement) End Sub

When it is called, the Execute() method of the Connection class examines and executes its (first) argument, in this case strStatement. If this method succeeds, it returns an object called a record set. We will study record sets in future lessons. Closing a Connection When using a connection, it consumes resources that other applications may need. Therefore, after using it, you should close it and free the resources it was using so they can be made available to the other parts of the computer. To close a connection, the Connection class is equipped with the Close() method. This can be done as follows:
Private Sub btnConnection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConnection.Click Dim conADO As ADODB.Connection Dim strConnection As String Dim strStatement As String

conADO = New ADODB.Connection strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'" strStatement = "Blah Blah Blah"

conADO.Open(strConnection) conADO.Execute(strStatement)

conADO.Close End Sub

The Tables of a Database Table Creation Introduction In the first lesson, we defined a database as one or more lists. A list in a database is called a table. The idea is that a table is an arrangement of the categories of information stored in a list and a table makes it easy to locate and manage the records of a list. To better explore lists, you should know how a table organizes its value. A table is made of one or more categories divided as columns. Consider the following example of a list of teachers of a high school: Last Name Pastore Andong Missiano Jones First Name Albert Gertrude Helena Celestine Main Subject Alternate Subject Math Physics Chemistry Static Physical Ed Comp Sciences Math

Notice that the first named are grouped in a common category, so are the last names and so on. This makes it easy to locate a category and possibly a value. Table Creation

To create a table, you start an expression with CREATE TABLE followed by the name of the table:
CREATE TABLE Name;

The CREATE and TABLE keywords must be used to create a table. The Name factor specifies the name of the new table. The Name of a Table After the CREATE TABLE expression, you must enter a name for the table. The name of a table can be very flexible. This flexibility can be overwhelming and confusing. To avoid these, there are suggestions and conventions we will apply when naming our tables:

The name of a table will start with a letter. In most cases, the name will start in uppercase Because we believe that a table represents a list of items, its name will be in plural. Examples are Students, Employees, Products When a name is a combination of words, each part will start in uppercase. Examples are Student Names or Sport Activities In most cases, we will avoid including space in a name.

Here is an example:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strCreate As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords1.mdb'", Nothing, Nothing, 0) strCreate = "CREATE TABLE Students . . .;"

conADO.Close

End Sub

After formulating the expression that creates the table, you can pass it to the Execute() method of a Connection variable. This would be done as follows:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click

Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strCreate As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords1.mdb'", Nothing, Nothing, 0) strCreate = "CREATE TABLE Students . . .;" conADO.Execute(strCreate, 0, 0) conADO.Close End Sub

Besides the CREATE TABLE expression followed by a name, there are other issues related to creating a table. We will review more details in future lessons. Table Maintenance The Tables Collection The tables of an ADO database are stored in a collection. To locate this collection, you can access the Tables property of the Catalog class of the ADOX namespace. Deleting a Table To remove a table from a database, create a DROP TABLE expression followed by the name of the table. The formula to use is:
DROP TABLE TableName;

Replace the TableName factor of our formula with the name of the table you want to delete. Here is an example:
Private Sub btnDeleteTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDeleteTable.Click Dim conSchoolRecords As New ADODB.Connection

conSchoolRecords.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'") conSchoolRecords.Execute("DROP TABLE Teachers;")

MsgBox("The Teachers table of the SchoolRecords database has been deleted.") conADO.Close End Sub

The Columns of a Table Columns Fundamentals Introduction In the previous lesson, we saw that a table was used to organize the values of a list by using categories of information. Here is an example:

Last Name First Name Main Class Pastore Andong Missiano Jones Albert Gertrude Helena Celestine

Years of Experience Math 4 Chemistry 8 Physical Ed 5 Comp Sciences 10

With this type of arrangement, each column holds a particular category of information. A table must have at least one column. This means that, to create a table using the CREATE TABLE TableName formula we introduced in the previous lesson, you must specify a column. Column Creation To create the columns of a table, on the right side of the name, type an opening and a closing parentheses. In the parentheses of the CREATE TABLE TableName() expression, the formula of creating a column is:
ColumnName DataType Options

Notice that there is only space that separates the sections of the formula. This formula is for creating one column. If you want the table to have more than one column, follow this formula as many times as possible but separate the sections with colons. This would be done as follows:
CREATE TABLE TableName(ColumnName DataType Options, ColumnName DataType Options)

In the next sections, we will review the factors of this formula. To create a table in ADO, you can pass the whole statement to the Execute() method of the Connection class.

Characteristics of a Column Introduction Like a table of a database, a column must have a name. As mentioned for a table, the name of a column is very flexible. Because of this, we will adopt the same types of naming conventions we reviewed for tables:

The name of a column will start with a letter. In most cases, the name will start in uppercase When a name is a combination of words, each part will start in uppercase. Examples are First Name or Date Hired In most cases, we will avoid including space in a name

When creating the table, set the name of the column in the ColumnName placeholder of our formula. Here is an example:
CREATE TABLE Students(FullName, DataType Options)

Notice that the name of the column is not included in quotes. The Types of Columns To exercise a good level of control over the values that can be entered or stored in a database, you can configure each column to allow some types of value and/or to exclude some other types. This is done by specifying an appropriate type of data for the column. To specify the data type of a column, pass the name of the data type as the second factor of the column. Text-Based Columns: If the fields under a column would be used to hold any type of value, including regular text, such a column is treated as string-based. There are various data types you can apply to such a column. You can specify the data type as Char, String or Varchar. Here are examples of three columns created with these types:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing,

0) strSQL = "CREATE TABLE Students(FirstName char, MiddleName String, " & _ "LastName varchar);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub

Each one of the char, string, or varchar data types would produce the same effect. A column with the string, the char, or the varchar data type allows any type of value made of any character up to 255 symbols. If you want the column to hold longer text, specify its data type as Text, Memo, NOTE, or LONGTEXT. Such a column can hold any type of text, any combination of characters, and symbols, up to 64000 characters. Here are examples:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ 0) & _ _ "Comments Memo, ShortTimeGoals Note, " & "LongTimeGoals LongText);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing, strSQL = "CREATE TABLE Employees(FullName String, JobDescription Text, "

Boolean Columns: If you want to create a column to hold only values as being true or being false, specify its data type as YESNO, BIT, or LOGICAL. Here are examples:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ 0) "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing, strSQL = "CREATE TABLE Employees(FullName String, IsFullTime Bit, " & _ "CanTeachVariousSubjects Logical, " & _ "IsMarried YesNo);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub

Byte and Integer1: If you want a column to hold natural numbers, you can specify its data type as Byte or Integer1. This is suited for a column that will hold small numeric values not to exceed 255. Here are examples:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ 0) "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing,

strSQL = "CREATE TABLE EmploymentStatus(StatusID Byte, Category Integer1);" conADO.Execute(strSQL, 0, 0) _ MessageBox.Show("A table named EmploymentStatus has been added to the " & "SchoolRecords.mdb database") conADO.Close End Sub

Short and Integer2: If you want the column to hold larger numbers that can exceed 255, specify its data type as SHORT or INTEGER2. Long: If the column will hold small to very large numbers, specify its data type as INT, INTEGER,

INTEGER4 or Long. Floating-Point Value With Single Precision: If you want to create a column that will hold regular decimal values without regards to precision on its value, specify its data type as Single. Floating-Point Value With Double Precision: If the values of a column will require a good level of precision, specify its data type as Double. Alternatively, you can specify the data type as Numeric. Here is an example:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing, 0) strSQL = "CREATE TABLE Students(FullName varchar, Height Single, " & _ "Weight Numeric, GPA Double);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub

Money and Currency Columns: If you want the values of a column to hold monetary values, specify its data type as Money or Currency. Here is an example:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing, 0) strSQL = "CREATE TABLE Employees(" & _ "FullName Text, " & _

"WeeklyHours Double, " & _ "HourlySalary Money, WeeklySalary Currency);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub

Both Money and Currency have the same effect. Date and Time: If you are creating a column whose values would consist of date, time, or both date and time, specify its data type as DATE or DATETIME. Here are examples:
Private Sub btnCreateTable_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateTable.Click Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass Dim strSQL As String

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'", Nothing, Nothing, 0) strSQL = "CREATE TABLE Employees(" & _ "FullName Text, " & _ "DateHired Date, " & _ "DateLastReviewed DateTime);" conADO.Execute(strSQL, 0, 0) conADO.Close End Sub

Both data types have the same effect in Microsoft Access. Binary: The binary data type can let a column accept any type of data but it is equipped to interpret the value. For example, it can be used to receive hexadecimal numbers. To specify this when creating a column, specify its data type as either BINARY or VARBINARY. Image: If you are creating a column that will hold external documents, such as pictures, formatted (from Microsoft Word for example), or spreadsheet, etc, specify its data type to one of the following: IMAGE, OLEOBJECT, LONGBINARY, or GENERAL.

Column Maintenance Introduction Column maintenance consists of adding a new column or deleting an existing column. Because the columns belong to a table, their maintenance is related to it. To perform this maintenance, you start with the ALTER TABLE expression followed by the name of the table. Adding a New Column After a table with one or more columns has been created, you can add a new column to it. To add a new column, after the ALTER TABLE statement and the name of the table, include an ADD COLUMN expression using the following formula:
ALTER TABLE TableName ADD COLUMN ColumnName DataType

The ColumnName factor must be a valid name for the new column and you must follow the rules for naming columns. The data type must be one of those we reviewed. Here is an example that adds a new string-based column named CellPhone to a table named Employees:
Private Sub btnAddColumn_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAddColumn.Click Dim conSchoolRecords As New ADODB.Connection

conSchoolRecords.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'") conSchoolRecords.Execute("ALTER TABLE Employees ADD COLUMN CellPhone string;")

MsgBox("A new column named CellPhone has been added to the Employees table.") conADO.Close End Sub

It is important to understand that the ADD COLUMN expression creates a new column at the end of the existing column(s). It cannot be used to insert a column in a table. Deleting a Column To delete a column, start with the ALTER TABLE expression followed by the name of the table. After the ALTER TABLE TableName expression, follow it with a DROP COLUMN expression

using this formula:


ALTER TABLE TableName DROP COLUMN ColumnName;

Replace the name of the undesired column with the ColumnName factor of our formula. Here is an example:
Private Sub btnDeleteColumn_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDeleteColumn.Click Dim conSchoolRecords As New ADODB.Connection

conSchoolRecords.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\SchoolRecords.mdb'") conSchoolRecords.Execute("ALTER TABLE Employees DROP COLUMN Comments;")

MsgBox("The Comments column has been deleted from the Employees table.") conADO.Close End Sub

The Records of a Database Data Entry Fundamentals Introduction After creating a table and its column(s), you can populate the database with data. You and the user can use either the table or the form but as mentioned previously, the form is sometimes the appropriate object to do this. Data entry consists of filling a database with the necessary values. A series of values that corresponds to same levels of columns is called a row or a record. Here are the database and the table we will use:
Private Sub btnPersons_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPersons.Click Dim catPeople As New ADOX.CatalogClass Dim conPeople As New ADODB.ConnectionClass

Dim strSQL As String

catPeople.Create("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb';") MsgBox("A new Microsoft JET database named People.mdb has been created")

conPeople.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ 0) "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, strSQL = "CREATE TABLE Persons(" & _ "PersonID COUNTER NOT NULL, " & _ "FirstName Text(20), " & _ "LastName Text(20), " & _ "Gender Text(20));" conPeople.Execute(strSQL, 0, 0) MessageBox.Show("A table named Persons has been created in the " & _ "People.mdb database")

conPeople.Close() End Sub

This creates a Microsoft JET database named People, followed by a table named Persons, and populates it with four records. New Record Creation Before performing data entry on a table, you must know how the table is structured, the sequence of its columns, the type of data that each column is made of. To enter data in a table, you start with the INSERT combined with the VALUES keywords. The statement uses the following syntax:
INSERT TableName VALUES(Column1, Column2, Column_n)

Alternatively, or to be more precise, you can specify that you are entering data in the table using the INTO keyword between the INSERT keyword and the TableName factor. This is done with the following syntax:
INSERT INTO TableName VALUES(Column1, Column2, Column_n)

The TableName factor must be a valid name of an existing table in the currently selected database. If the name is wrong, the SQL interpreter would simply consider that the table you are referring to doesn't exist. Consequently, you would receive an error. The VALUES keyword indicates that you are ready to list the values of the columns. The values of the columns must be included in parentheses. Specify the value of each column in the parentheses that follow the VALUES keyword: Boolean Values: If the column is Boolean-based, you must specify its value as 0 or 1. Numeric Values: If the column is a numeric type and if the number is an integer, you should provide a valid natural number without the decimal separator. If the column is for a decimal number, you can type the value with its character separator (the period for US English). Character and String Values: If the data type of a column is a string type, you should include its value between double-quotes. For example, a shelf number can be specified as 'HHR-604' and a middle initial can be given as 'D'. Date and Time Values: If the column was created for a date or a time data type, you should/must use an appropriate formula with the year represented by 2 or 4 digits. You should also include the date in single-quotes. If you want to specify the year with 2 digits, use the formula:
'yy-mm-dd'

Or
'yy/mm/dd'

You can use the dash symbol "-" or the forward slash "/" as the date separator. An alternative to representing a year is with 4 digits. In this case, you would use the formulas:
'yyyy-mm-dd'

Or
'yyyy/mm/dd'

The year with 4 digits is more precise as it properly expresses a complete year. A month from January to September can be represented as 1, 2, 3, 4, 5, 6, 7, 8, or 9. Day numbers follow the same logic. Adjacent Data entry The most common technique of performing data entry requires that you know the sequence of columns of the table in which you want to enter data. With this subsequent list in mind, enter the value of each field in its correct position.

During data entry on adjacent fields, if you don't have a value for a numeric field, you should type 0 as its value. For a string field whose data you don't have and cannot provide, type two single-quotes to specify an empty field. Here is an example:
Private Sub btnCreateRecord_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateRecord.Click Dim conPeople As New ADODB.ConnectionClass

conPeople.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ 0) "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, conPeople.Execute("INSERT INTO Persons(FirstName, LastName, Gender) " & _ "VALUES('James', 'Carlton', 'Male');") MsgBox("A new record has been created in the Persons table") conSchoolRecords.Close() End Sub

Random Data Entry The adjacent data entry requires that you know the position of each column. The SQL provides an alternative that allows you to perform data entry using the name of a column instead of its position. This allows you to provide the values of fields in any order of your choice. To perform data entry at random, you must provide a list of the columns of the table in the order of your choice. You can either use all columns or provide a list of the same columns but in your own order. Here is an example:
Private Sub btnCreateRecord_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreateRecord.Click Dim conPeople As New ADODB.ConnectionClass

conPeople.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) conPeople.Execute("INSERT INTO Persons(LastName, Gender, FirstName) " & _ "VALUES('Germain', 'Male', 'Ndongo');") MsgBox("A new record has been created in the Persons table")

conPeople.Close() End Sub

You don't have to provide data for all columns, just those you want, in the order you want. To do this, enter the names of the desired columns on the right side of the name of the table, in parentheses. The syntax used would be:
INSERT TableName(ColumnName1, Columnname2, ColumnName_n) VALUES(ValueFormColumnName1, ValueFormColumnName2, ValueFormColumnName_n);

Data Entry Assistance The Nullity of a Field When performing data entry, you can expect the user to skip any column whose value is not available and move to the next. In some cases, you may require that the value of a column be specified before the user can move on. If you are creating a column and if you want to let the user add or not add a value for the column, type the NULL keyword on the right side of the data type. If you want to require a value for the column, type NOT NULL. Here are examples:
Private Sub btnVideoCollection_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnVideoCollection.Click Dim catADOX As New ADOX.Catalog

catADOX.Create("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\VideoCollection.mdb';") MsgBox("A new Microsoft JET database named VideoCollection.mdb has been created")

End Sub

Private Sub btnVideos_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnVideos.Click Dim conVideos As New ADODB.Connection

conVideos.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\VideoCollection.mdb'") conVideos.Execute("CREATE TABLE Videos(" & _ "VideoTitle "Director STRING NOT NULL, " & _ STRING NULL, " & _

"YearReleased SHORT, " & _ "Rating conVideos.Close() End Sub BYTE NULL);")

In this case, when performing data entry, the user must always provide a value for the VideoTitle column in order to create a record. If you omit to specify the nullity of a field, it is assumed NULL; that's the case for the YearReleased column of the above Videos table. Auto-Increment When we study relationships, we will see that, on a table, each record should be uniquely identified. This should be the case even if many records seem to have the same values for each column. We saw already that you can require that the user provide a value for each record of a certain column. In some cases, the user may not have the right value for a column but at the time, the record would need to be created, even if it is temporary. To solve this type of problem and many others, you can create a column that provides its own value. On the other hand, to create a special column that can be used to uniquely identify each record, you can apply an integer data type to it but ask the database engine to automatically provide a numeric value for the column. If you are creating the column, you can specify its data type as either COUNTER or AUTOINCREMENT. Only one column of a table can have one of these data types. Here is an example:
Private Sub btnVideos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVideos.Click Dim conVideos As New ADODB.Connection

conVideos.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\VideoCollection.mdb'") conVideos.Execute("CREATE TABLE Videos(" & _ "ShelfNumber "VideoTitle COUNTER, " & _ STRING NOT NULL, " & _

"Director

STRING NULL, " & _

"YearReleased SHORT, " & _ "Rating conVideos.Close() End Sub BYTE NULL);")

By default, when you apply the COUNTER or the AUTOINCREMENT data type, when the user creates the first record, the field int the auto-incrementing column receives a number of 1. If the user creates a second record, the auto-incrementing value receives a number of 2, and so on. If you want, you can make the first record receive a number other than 1. You can also make it increment to a value other than 1. To apply this feature, the COUNTER and the AUTOINCREMENT types use a seed as their parentheses:
COUNTER(x,y)

or
AUTOINCREMENT(x,y)

The x value represents the starting value of the records. The y value specifies how much would be added to a value to get the next. Fields Sizes When reviewing the data types available for columns, we saw that some of them could use a stringbased data type, namely TEXT, CHAR, or VARCHAR. By default, if you create a table and you set a column's data type to TEXT, CHAR, or VARCHAR, it is made to hold 255 characters. If you want, you can control the maximum number of characters that would be allowed in a column during data entry. To specify the number of characters of the string-based column, add the parentheses to the TEXT, the CHAR, or the VARCHAR data types, and in the parentheses, enter the desired number. Here are examples:
Private Sub btnVideos_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnVideos.Click Dim conVideos As New ADODB.Connection

conVideos.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\VideoCollection.mdb'") conVideos.Execute("CREATE TABLE Videos(" & _

"ShelfNumber "VideoTitle "Director

COUNTER, " & _ STRING(120) NOT NULL, " & _ VARCHAR(80) NULL, " & _

"YearReleased SHORT, " & _ "Rating conVideos.Close() End Sub TEXT(20) NULL);")

Default Values A default value allows a column to use a value that is supposed to be common to most cells of a particular column. The default value can be set as a constant value or it can use a function that would adapt to the time the value is needed. To specify a default value, after the name and the data type of a column, type DEFAULT and assign it the desired value, based on the data type. Here is an example:
Private Sub btnVideos_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnVideos.Click Dim conVideos As New ADODB.Connection

conVideos.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\VideoCollection.mdb'") conVideos.Execute("CREATE TABLE Videos(" & _ "ShelfNumber "VideoTitle "Director COUNTER, " & _ STRING(120) NOT NULL, " & _ VARCHAR(80) NULL, " & _

"YearReleased SHORT, " & _ "Rating conVideos.Close() End Sub TEXT(20) NULL Default='PG-13');")

Introduction to Record Sets

A Record Set Object Introduction After creating a table, you can fill it with records. You can also create a list (called a query) that selects a few records from a table. The records that a table holds are referred to as a set of records or a record set. To support them as an entity, the ADO library provides an object called a Recordset. Here are the database and the table we will use:
Private Sub btnPersons_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPersons.Click Dim catPeople As New ADOX.CatalogClass Dim conPeople As New ADODB.ConnectionClass Dim strSQL As String catPeople.Create("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb';") MsgBox("A new Microsoft JET database named People.mdb has been created") conPeople.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, strSQL = "CREATE TABLE Persons(" & _ "PersonID COUNTER NOT NULL, " & _ "FirstName Text(20), " & _ "LastName Text(20), " & _ "Gender Text(20));" conPeople.Execute(strSQL, 0, 0) MsgBox("A table named Persons has been created in the " & _ "People.mdb database") conPeople.Execute("INSERT INTO Persons(FirstName, LastName, Gender) "VALUES('James', 'Carlton', 'Male');") conPeople.Execute("INSERT INTO Persons(FirstName, LastName, Gender) "VALUES('Hermine', 'Nguyen', 'Female');") conPeople.Execute("INSERT INTO Persons(FirstName, LastName, Gender) "VALUES('Paul', 'Yamaguchi', 'Male');") conPeople.Execute("INSERT INTO Persons(FirstName, LastName, Gender) "VALUES('Justice', 'Ville', 'Unknown');") MsgBox("New records have been created in the Persons table") End Sub conPeople.Close() " & _ " & _ " & _ " & _

0)

This creates a Microsoft JET database named People, followed by a table named Persons, and populates it with four records. The Type of Recordset Objects When creating a record set, you can specify whether to use one or more tables and what record(s) would be included. How the record set is created, how many tables it would have, how many records,

and what types of operations can be performed on the records lead to various types of record sets:

Table Recordset: If your Recordset object includes only one table, it is referred to a Table record set Dynaset: If a record set includes one or more tables, it is called a Dynaset. This type allows adding, editing, updating, or deleting records that are part of the Recordset object Snapshot: A record set is called a Snapshot if it allows you to view the records of one or more tables, navigating back and forth in the set, but you cannot make changes on the records Forward-Only Recordset: A Recordset object is referred to as Forward-Only if you can view its records without changing them and you can only move forward. This means that, if you get to a record, examine it, and move to the next record, you cannot refer back to a record you left behind Dynamic Recordset: If you create a list based on data from one or more tables and allows the users to navigate back and forth with the ability to make changes to records, this type of record set is referred to as Dynamic.

Creating a Recordset Object Normally, you firstly create a record set by populating a table with the desired values. To create a Recordset object, start by declaring a variable of type ADODB.Recordset. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.Recordset End Sub

Before using the record set, use the New operator to allocate memory for it. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.Recordset rstPeople = New ADODB.Recordset End Sub

Opening the Recordset After declaring the variable, to start creating the recordset, you can open the Open() method of the RecordsetClass class. It's syntax is:
Open([Source As Object], [ActiveConnection As Object], [CursorType As ADODB.CursorTypeEnum = ADODB.CursorTypeEnum.adOpenUnspecified], [LockType As ADODB.LockTypeEnum = ADODB.LockTypeEnum.adLockUnspecified, [Options As Integer = -1])

This method takes five arguments, only the first two are required. Characteristics of a Record Set

The Source To work on a record set, you must communicate what list of values, such as a table or else, would be considered in the set. To specify a table as the source of data, pass it, as a string, as the first argument to the Recordset.Open() method. This can be done as follows:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass rstPeople = New ADODB.RecordsetClass rstPeople.Open("Persons", . . .) End Sub rstPeople.Close()

This specifies that the source of data will be a table named Persons. The Connection to a Record Set When creating a recordset, you must specify how the connection to the database would be established. To support this, the RecordsetClass class is equipped with a property named ActiveConnection, which is of type String. To specify this property, you can first create a ConnectionClass object using the techniques we reviewed in previewed lessons. After defining the object, you can pass it as the second argument to the RecordsetClass.Open() method. This can be done as follows:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass rstPeople = New ADODB.RecordsetClass conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("Persons", conADO) End Sub rstPeople.Close()

This creates a connection to a database named People and uses it for the new RecordsetClass object. A Cursor In many environments, a database will need to be accessed by more than one computer. This means that, when creating a RecordsetClass object, you need to keep different factors in mind. For example, you (actually your user) may be accessing a record or a series of records at the same time with someone else from another computer. In some cases, there may usually be only one person using a database and there might occasionally be someone else but unlikely, although possible. In some other cases, such as on the Internet or in a big enterprise, there might be many people accessing, or trying to

access, a database, or a specific set of records, at the same time. Imagine you are working on a large database such as a bank application that has thousands or millions of records (such as thousands or millions of customers). If you want to perform an operation on the customers, you may have to deal with many or all records. You may also have to deal with the fact that other people are accessing the same records like you, at the same time. Normally, some operations don't require you to have access to all records, at least not all the time. When working on records, thus when creating a RecordsetClass object, you can specify a way to isolate a range of records and deal only with that range. The range of records that you select is called a cursor. Because a cursor plays a tremendous role in a record set, there are different options when using it. To support these options, the ADODB namespace is equipped with an enumeration named CursorTypeEnum. There are various types of cursors:

A static cursor holds a constant set of records. Suppose you create a record set and open it. Also suppose that either you only or other people besides you are working on the same record set. You get to a record and start viewing it (or even working on it). After using that record, you move to another record, and you can do this back and forth as you wish. Suppose that, while doing this back and forth navigation (we will learn later on how to programmatically navigate through a record set), another person has accessed a record that is part of your record set and made a change. If using a static cursor, every time you visit the record set, it shows the same records the way they were when you opened the record set. It would not show the changes that have taken place. This is why it is called a static cursor. A static cursor is appropriate if you are not interested to know what changes have taken place ever since you opened the record set. A static cursor is represented with the ADODB.CursorTypeEnum.adOpenStatic value. A cursor is referred to as forward-only if it allows you to move forward through the records. Here is how it works. Suppose that you create a Recordset object and specify its cursor. Suppose that, while using the record set, you get to a record that was set as the start point of your cursor. Also, suppose that either you only or other people besides you are working on the same record. If you make a change on the current record, the other people will be notified. If other people make a change on the current record, you also would know. After using that record, you move to the next. With the forward-only cursor, you cannot move back to a record you left already. This means that, even if you are still working on the record set, if there are changes performed on a record you left behind (for example, if another person who is working on the same record changes something on a record that you passed already), you cannot know and you cannot find out because you cannot go back to a record left behind. If this becomes a necessity, you can close the cursor and re-open it. A forward-only cursor is appropriate if you don't need to navigate back and forth among the records of a record set. Because of the way it works, if you access the RecordCount property of a forward-only cursor, it would produce -1. This type of cursor is represented by the ADODB.CursorTypeEnum.adOpenForwardOnly value. A cursor is called dynamic if it detects and shows all changes that are occurring in a record set,

whether the changes are caused by you or by other people who are accessing the record set at the same time. This type of cursor is appropriate if you want to know, live, what is going on with the record set you are working with. To specify a dynamic cursor, use the ADODB.CursorTypeEnum.adOpenDynamic value. A key set cursor creates and saves a key for each record that has been modified since the record set was opened. If you access the record, the key is used to check the data of the record set. A key set cursor is created using the ADODB.CursorTypeEnum.adOpenKeyset value.

If you don't specify a cursor, the ADODB.CursorTypeEnum.adOpenUnspecified value is used as the default cursor. Otherwise, to specify a cursor, pass the desired value as the third argument to the RecordsetClass.Open() method. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass rstPeople = New ADODB.Recordset Dim fldEach As ADODB.Field conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("Persons", _ conADO, _ ADODB.CursorTypeEnum.adOpenDynamic) rstPeople.Close() End Sub

This specifies a dynamic cursor on the recordset. The Lock Type Imagine that, after creating a record set and working on it, you want to control who else can have access to the records of the set you are using. To exercise this control, you can create a "lock". This allows you, for example, to prevent other people from changing the records until you have finished with them. To support locking, the ADODB namespace is equipped with an enumeration named LockTypeEnum, which defines various options:

When a computer connects to a database, its user may need to make changes to various records at the same time, such as deleting a range of records or changing many records at the same time (such as giving a raise to many employees), instead of making one change, then another, then another. For this type of scenario, when the user accesses the records, instead of monopolizing them and waiting for the user to finish an operation that could take long, you can download the records on the user's computer, and disconnect the user from the database. The user would then make the necessary changes. When the user is ready to commit the changes, you can then reconnect to the data source and submit the changes. This type of lock is referred to as batch optimistic. This lock is supported through the ADODB.LockTypeEnum.adLockBatchOptimistic value You may have a database that a few different people access at the same time. If the database is

small enough, which is the case for restricted environment, the likelihood of two people editing or updating the same record (at the same time) may be low. In this case, you can indicate that you want to lock the record only when necessary. In this case, you use what is referred to as optimistic locking. This lock is implemented using the ADODB.LockTypeEnum.adLockOptimistic value The above two options assume that you would lock many records to apply the indicated scenarios. If you prefer to lock one record at a time, you can use what is referred to as pessimistic locking. This lock is done using the ADODB.LockTypeEnum.adLockPessimistic value The above three scenarios allow a user to edit and/or update the records that are included in the set. In some cases, you may want to prevent any editing or update on the records while the set is being accessed. In this case, you can set the records to read-only. This lock can be set using the ADODB.LockTypeEnum.adLockReadOnly value

If you don't want to specify the type of lock system to use on a record set, use the ADODB.LockTypeEnum.adLockUnspecified value, which is the default value. Otherwise, to specify the lock type, pass the desired value as the fourth argument to the RecordsetClass.Open() method. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass rstPeople = New ADODB.Recordset Dim fldEach As ADODB.Field conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("Persons", _ conADO, _ ADODB.CursorTypeEnum.adOpenDynamic, _ ADODB.LockTypeEnum.adLockOptimistic) End Sub rstPeople.Close()

This uses the adLockOptimistic as the type of lock used on the recordset. Introduction to SQL The Structured Query Language Introduction The Structured Query Language, abbreviated SQL, is a universal language used to create and managed computer databases. It is used in all popular database environments, including Microsoft SQL Server, Oracle, Borland/Corel Paradox, Microsoft Access, etc. SQL can be pronounced Sequel or S. Q. L. On this site, we will consider the Sequel

pronunciation. A SQL Statement When using SQL, you write a relatively short sections of code and view its result. Code based on SQL is referred to as a SQL statement. When writing an expression, SQL is not case-sensitive. This means that Case, case, and CASE represent the same word. This applies to keywords of the SQL or words that you will add in your expressions. The most fundamental operator used in the SQL is called SELECT. This operator is primarily used to display a value to the user. In this simple case, it uses the following formula:
SELECT Value;

The value on the right side of SELECT must be appropriate. The value to select can be a number. Here is an example:
SELECT 48;

The value can also be a string or else. In most cases, you will be selecting one or more columns of a table. After creating the SELECT expression, you can pass it as the first argument to the RecordsetClass.Open() method. Column Selection Introduction When creating a recordset, you can use the whole table, including all of its columns. An alternative is to select only one or more columns from a table. In this case, the formula used on the SELECT operator is:
SELECT What FROM WhatObject;

The What factor of our syntax is the name of the column(s) of a table. The WhatObject factor can be the name of a table. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass = New ADODB.Recordset Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0)

rstPeople.Open("SELECT LastName FROM Persons;", conADO)

rstPeople.Close() End Sub

To consider more than one column in a statement, you can list them in the What factor of our formula, separating them with a comma except for the last column. The syntax you would use is:
SELECT Column1, Column2, Column_n FROM WhatObject;

Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass = New ADODB.Recordset Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("SELECT FirstName, LastName, Gender FROM Persons;", conADO)

rstPeople.Close() End Sub

In the previous lesson, we saw that, to select everything, that is, all columns, from a table, you could pass the name of the column as the first argument to the RecordsetClass.Open() method. To get the same effect, you can use the asterisk in place of the What factor of our formula. This would be done as follows:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass = New ADODB.Recordset Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0)

rstPeople.Open("SELECT * FROM Persons;", conADO)

rstPeople.Close() End Sub

SELECT This AS That If you create a SELECT statement that specifies the name or names of columns, the name of each column is used to represent it. If you want, you can specify a different string, sometimes named a caption, that would represent the column. To do this, the formula to use is:
SELECT Value As Caption;

The words SELECT and AS are required. As mentioned already, SELECT would be used to specify a value and AS in this case allows you to specify a caption of your choice. The caption can be made of a word but the word cannot be one of the SQL's keywords. If the Caption is made of more than one word, you can include between an opening and a closing square brackets. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass

rstPeople = New ADODB.Recordset Dim fldEach As ADODB.Field

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("SELECT LastName As [Last Name] FROM Persons;", _ conADO)

For Each fldEach In rstPeople.Fields MsgBox(fldEach.Value) Next

rstPeople.Close()

End Sub

In the same way, you can apply the AS keyword to as many columns as you want by separating them with commas. Here is an example:
Private Sub btnRecordset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRecordset.Click Dim rstPeople As ADODB.RecordsetClass Dim conADO As ADODB.ConnectionClass = New ADODB.ConnectionClass

rstPeople = New ADODB.Recordset Dim fldEach As ADODB.Field

conADO.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source='C:\Programs\People.mdb'", Nothing, Nothing, 0) rstPeople.Open("SELECT LastName AS [Last Name], Gender AS Sex FROM Persons;", _ conADO)

For Each fldEach In rstPeople.Fields MsgBox(fldEach.Value) Next

rstPeople.Close() End Sub

In the same way, you can mix number-based and string-based columns.

ADO Record Navigation Introduction A recordset is a technique of getting all records from a table or by isolating a few records based on a rule called a criterion. After getting those records, one of the actions you can perform is to view them. Record navigation consists of visiting the records, one at a time, sometimes in one direction or back

and forth. Imagine you have created a database named People and you created a table named Persons with the following columns: Column Name PersonID FirstName LastName Gender Data Type COUNTER Text(20) Text(20) Text(20)

After creating the table, you can populate it with a few records The Field Class To perform record navigation, you must communicate what Windows control of a form would display what field of a recordset. This action is referred to as data binding. To bind a column to a control, you must identify that column. To support columns, the ADO library identifies each column as a field. In the ADO namespace of the .NET Framework, a column is represented with the Field class. Like a column of a table, a Field object is represented by a Name property. Another important characteristic of a column is the value under it. This is represented in the Field class by the Value property. The Fields Collection When creating a recordset, you have the option of using all columns of a table or selecting only one or a few of them. After creating the recordset, its columns are stored in a collection called Fields. To recognize the columns of a recordset as an entity, the Recordset interface is equipped with a property called Fields. To identify a Field object of a Fields collection, you use its index. To do this, you have two main alternatives. You can identify a column using its position, also called its index, in the collection. As an alternative, you can pass the name of the column as index. Record Navigation After binding the columns to the Windows controls of a form, you can provide a few buttons to the form for record navigation. To move from one record to another, the Recordset class is equipped with appropriate methods. Their names are:

MoveFirst: Moves the cursor to the first record MovePrevious: Moves the cursor to the record previous of the current record MoveNext: Moves the cursor to the next record of the current record MoveLast: Moves the cursor to the last record

Move: Moves the cursor to a position specified by passing a number as the desired position

The Beginning and the Last Positions While navigating among records, you should make sure you don't move below the first record. To check the position of the cursor with regards to the first record, you can use the BOF Boolean property. When the cursor is at the beginning of the recordset, this property has a value of true. When moving to next records, make sure you don't pass the last record. To check whether the cursor is at the last record, check the value of the EOF Boolean property of the recordset. If this property has a True value, then you are on the last record. Here is code that illustrates record navigation:

Public Class Form1 Dim rstPeople as ADODB.Recordset Dim conPeople As ADODB.Connection Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load rstPeople = New ADODB.Recordset conPeople = New ADODB.Connection conPeople.Open("Provider='Microsoft.JET.OLEDB.4.0';" & _ "Data Source='C:\\Programs\\People.mdb';") rstPeople.Open("Persons", _ conPeople, _ ADODB.CursorTypeEnum.adOpenStatic, _ ADODB.LockTypeEnum.adLockOptimistic, 0) btnFirst_Click(sender, e) End Sub Private Sub RecordNavigator() txtPersonID.Text = rstPeople.Fields("PersonID").Value txtFirstName.Text = rstPeople.Fields("FirstName").Value txtLastName.Text = rstPeople.Fields("LastName").Value cboGenders.Text = rstPeople.Fields("Gender").Value

End Sub Private Sub btnFirst_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFirst.Click rstPeople.MoveFirst() RecordNavigator() End Sub Private Sub btnPrevious_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrevious.Click rstPeople.MovePrevious() If Not rstPeople.BOF Then RecordNavigator() Else btnFirst_Click(sender, e) End If End Sub Private Sub btnNext_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnNext.Click rstPeople.MoveNext() If Not rstPeople.EOF Then RecordNavigator() Else btnLast_Click(sender, e) End If End Sub Private Sub btnLast_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLast.Click rstPeople.MoveLast() RecordNavigator() End Sub Private Sub Form1_FormClosing(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles MyBase.FormClosing rstPeople.Close() conPeople.Close() End Sub Private Sub btnClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClose.Click End End Sub End Class

You might also like