action query <definition>
action query

A query that moves or changes data.  Action queries include append, delete, make-table, and update queries.  Delete and update queries change existing data; append and make-table queries move existing data.  In contrast, select queries return data records.  A SQL pass-through query may also be an action query.


action QueryDef <definition>
action QueryDef

A data access object that contains the definition of an action query.  An action QueryDef object is used only with the Execute method, and it moves or changes data instead of returning rows.


aggregate function <definition>
aggregate function

A function, such as Count, Avg, and Var, used in creating a query that calculates totals.  In writing expressions and in programming, you can use SQL aggregate functions (including the three listed above) and domain aggregate functions to determine various statistics.


alias <definition>
alias

In Visual Basic, an alternate name you give to an external procedure to avoid conflict with a Visual Basic keyword, global variable, constant, or a name not allowed by the standard naming conventions.

In SQL, an alternate name you give to a field or expression in a SELECT statement (using the AS clause), to make it shorter or more meaningful or to prevent name conflicts when performing SQL queries using expressions that don't return names or in a query that uses a self-join.


ANSI Character Set <definition>
ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used by Microsoft Windows that you can use to represent up to 256 characters (0 [image] 255) using your keyboard.  The first 128 characters (0 [image] 127) correspond to the letters and symbols on a standard U.S. keyboard.  The second 128 characters (128 [image] 255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


append query <definition>
append query

An action query that adds new records to the end of an existing table or query.  Append queries don't return records (rows).


argument <definition>
argument

A constant, variable, or expression that supplies additional information to an action, procedure, or method. You use an argument with an operand in an expression to supply additional information required by some action.


ASCII Character Set <definition>
ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard.  The ASCII character set is the same as the first 128 characters (0 [image] 127) in the ANSI character set.


asterisk <definition>
asterisk

A character (*) used as a wildcard in SQL LIKE expressions to accept any string of characters.  For example, the expression LIKE "*town*" accepts any name containing the string "town."

When you create a query or enter an SQL statement, use the asterisk to include all the fields that currently exist in the underlying table or query.  For example, SELECT * FROM MyTable returns all fields (columns) from the table.


attached table <definition>
attached table

A table in another database linked to a Microsoft Jet database.  Data for attached tables remains in the external database where it can be manipulated by other applications. (Also known as linked tables.)


autonumber field <definition>
autonumber field

See counter field.


base table <definition>
base table

A table in a Microsoft Jet database.  You can manipulate the structure of a base table using the data access objects or data definition SQL statements, and you can modify data in a base table using Recordset objects or action queries.


bookmark <definition>
bookmark

A property of the Recordset object or a form that contains a system-generated string identifying the current record. If you assign the Bookmark value to a variable and then move to another record, you can make the earlier record current again by setting the Bookmark property to that string variable.


Boolean data type <definition>
Boolean data type

A True/False or yes/no value.  Boolean values are usually stored in Bit fields in a Microsoft Jet database; however, some databases don't support this data type directly.


Boolean expression <definition>
Boolean expression

An expression that evaluates to either True or False.


bound control <definition>
bound control

A data-aware control that can provide access to a specific field in a database through a Data control.  A data-aware control can be bound to a Data control through its DataSource and DataField properties.  When a Data control moves from one record to the next, all bound controls connected to the Data control change to display data from fields in the current record.  When users change data in a bound control and then move to a different record, the changes are automatically saved in the database.


Byte data type <definition>
Byte data type

A fundamental data type used to hold small positive integer numbers ranging from 0 to 255.


Cartesian product <definition>
Cartesian product

The result of joining two relational tables, producing all possible ordered combinations of rows from the first table with all rows from the second table.

Generally, a cartesian product results from executing a SQL SELECT statement referencing two or more tables in the FROM clause and not including a WHERE or JOIN clause that indicates how the tables are to be joined.


cascade delete <definition>
cascade delete

For relationships that enforce referential integrity between tables, an option that causes the deletion of a record from the primary table to automatically delete all related records in the related foreign table or tables.

For example, suppose you establish a relationship between a Customers (Primary) table and an Orders (Foreign) table with the cascade delete option enabled.  When a record in the Customers table is deleted, all orders associated with that customer would also be deleted in the Foreign Orders table.


cascade update <definition>
cascade update

For relationships enforcing referential integrity between tables, an option that causes a change to the primary key in a record in the Primary table to automatically update the foreign key in all related records in the related Foreign table or tables.

For example, suppose you establish a relationship between a Customers (Primary) table and an Orders (Foreign) table with the cascade update option enabled.  When the primary key in a record in the Customers table is changed, all orders associated with that customer would also be changed in the Foreign Orders table.


cascade <definition>
cascade

The process of one action triggering another action.  For example, when a cascading update relationship is defined for two (or more) tables, an update to the primary key in the primary table automatically triggers (cascades) changes to the foreign table.


case-sensitive <definition>
case-sensitive

Capable of distinguishing between uppercase and lowercase letters.  A case-sensitive search finds only text that is an exact match of uppercase and lowercase letters.  Such a search would, for instance, treat “ZeroLengthStr” and “zerolengthstr” as different.  Microsoft Jet database operations are not case-sensitive.  However, case sensitivity is a feature of some other database management systems.


class <definition>
class

The formal definition of an object.  The class acts as the template from which an instance of an object is created at run time.  The class defines the properties of the object and the methods used to control the object's behavior.


CLSID (class ID) <definition>
CLSID (class ID)

A unique identifier of an application that is stored in the Windows Registry.  OLE uses this value to determine where the .exe or .dll code for this class resides.  Because the locations of CLSIDs never change and CLSIDs always point to the correct version of files, users are insulated from file and path name changes. A CLSID is a GUID data type in string format.


collection <definition>
collection

An object that contains a set of related objects.  An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary.


column <definition>
column

In a relational database, a column is synonymous with a field in a nonrelational database.  A column defines the data type, size, and other attributes of one field of a row (record) of data.  All columns taken as a set define a row (record) in the database.  An individual column contains data related in type and purpose throughout the table; that is, a column's definition doesn’t change from row to row.


commit <definition>
commit

To accept a pending transaction.  If you use transaction processing and begin a transaction using data access, none of the changes made in the transaction are written to the database until you commit or accept the transaction.


compile error <definition>
compile error

An error that occurs during compile time as the result of incorrectly constructed code.


consistent <definition>
consistent

The state of a multiple-table Recordset object that allows you to perform only updates that result in a consistent view of the data.  For example, in a Recordset that is a join of two or more tables (a one-to-many relationship), a consistent query would not allow you to set the many-side key to a value that isn’t in the one-side table.


control <definition>
control

An object you can place on a form that has its own set of recognized properties and events.  You use controls to receive user input, display output, and trigger event procedures.  You can manipulate most controls using methods.  Some controls are interactive (responsive to user actions), while others are static (accessible only through code).


copy buffer <definition>
copy buffer

A location created by the Microsoft Jet database engine for the contents of a record that is open for editing.  The Edit method copies the current record to the copy buffer; the AddNew method clears the buffer for a new record and sets the default values; and the Update method saves the data from the copy buffer to the database, replacing the current record or inserting the new record.  Any statement that resets or moves the current record pointer discards the copy buffer.  For example, using the MoveNext method or changing the Index property of a table would discard the contents of the copy buffer.


connect string <definition>
connect string

A string used to define the source of data for an external database.  The connect string is usually assigned to the Connect property of a QueryDef object or Data control or as an argument to the OpenDatabase method.


Counter data type <definition>
Counter data type

A Long data type field in a table where the field Attributes property has the dbAutoIncrement option bit set.  A  counter field is automatically incremented by 1 when a new record is added to the table.  Counter fields are not intended to be updated by the user.


counter field <definition>
counter field

A field that assigns the next consecutive number for each successive record added in the same field.  A counter field always uses the Long data type.  (Also known as an autonumber field.)


criteria <definition>
criteria

A set of limiting conditions, such as = "Denmark" (meaning equal to Denmark) or > 30000, used in creating a query or filter to show a specific set of records.


crosstab query <definition>
crosstab query

A query that returns data in a spreadsheet type format using fields you specify as row and column headings, and that can return summary data.


Currency data type <definition>
Currency data type

A data type that is useful for calculations involving money or for fixed-point calculations in which accuracy is extremely important.  This data type is used to store numbers with up to 11 digits to the left of the decimal point and 4 digits to the right.  The type-declaration character in Visual Basic is @.  Because the Currency data type uses discrete values for all amounts, binary round-off isn’t a factor when calculating totals.


current database <definition>
current database

The Database object returned by the CurrentDB( ) function.  A reference of DBEngine.Workspaces(0).Databases(0) returns the first database opened.  Not all Microsoft Jet database engine clients support the concept of a "current" database.  This concept isn’t supported in Visual Basic version 4.0.


current index <definition>
current index

For an indexed table-type Recordset object, the index most recently set with the Index property.  This index is the basis for ordering records in a table-type Recordset, and is used by the Seek method to locate records.  A Recordset object can have more than one index but can use only one index at a time (although a TableDef object may have several indexes defined on it).  The Microsoft Jet database engine may use more than one index to evaluate a query.


current record <definition>
current record

The record in a Recordset object that you can use to modify or examine data.  Use the Move methods to reposition the current record in a recordset.  Use the Find methods (with a dynaset- or snapshot-type Recordset object) or the Seek method (with a table-type Recordset object) to change the current record position according to specific criteria.

Only one record in a Recordset can be the current record; however, a Recordset may have no current record.  For example, after a dynaset-type Recordset record has been deleted, or when a Recordset has no records, the current record is undefined.  In this case, operations that refer to the current record result in a trappable error.


current transaction <definition>
current transaction

All changes made to a Recordset object after you use the last BeginTrans method and before you use the Rollback or CommitTrans method.


data access object <definition>
data access object

An object that is defined by the Microsoft Jet database engine.  You use data access objects, such as the Database, TableDef, Recordset and QueryDef objects, to represent objects that are used to organize and manipulate data, such as tables and queries, in code.


data-definition query <definition>
data-definition query

An SQL-specific query that can create, alter, or delete a table, or create or delete an index in a database.


data page <definition>
data page

A portion of the database file in which record data is stored.  Depending on the size of the records, a data page may contain more than one record.  A data page in a Microsoft Jet database is 2K bytes.


data source <definition>
data source

A named Open DataBase Connectivity (ODBC) resource that specifies the location, driver type, and other parameters needed by an ODBC driver to access an ODBC database.  A data source can be any source of database information.


data type <definition>
data type

The characteristics of a variable that determine what kind of data the variable can hold. Data types include Byte, Boolean, Currency, Date, Double, Integer, Long, OLE Object, Single, String, Variant (default), user-defined types (created with the Type statement), and object data types, which include host-defined object data types and data access object types.


database <definition>
database

A set of data related to a particular topic or purpose.  A database contains tables and can also contain queries and indexes as well as table relationships, table and field validation criteria, and linkages to external data sources.


database administration <definition>
database administration

Activities required to preserve the integrity and security of a database, such as maintaining user permissions and backing up, compacting, and repairing the database.


database engine <definition>
database engine

That part of the database system that retrieves data from and stores data in user and system databases.


database management system (DBMS) <definition>
database management system (DBMS)

Software used to organize, analyze, and modify information stored in a database. The Microsoft SQL Server and the Microsoft Jet database engine are examples of database management systems.


database objects <definition>
database objects

The database objects are Recordset, Field, Index, QueryDef, TableDef, Relation, User, Group, Property, and Document.


Database object <definition>
Database object

A Database object is a logical representation of a physical database.  A database is a set of data related to a specific topic or purpose.  A database contains tables and can also contain queries and indexes as well as table relationships, table and field validation criteria, and linkages to external data sources.


date literal <definition>
date literal

Any sequence of characters with a valid format that is surrounded by number signs (#).  Valid formats include the date format specified by the locale settings for your code or the universal date format.

For example, #12/31/92# is the date literal that represents December 31, 1992 where English-U.S. is the locale setting for your application.  Use date literals to maximize portability across national languages.


dates and times <definition>
dates and times

Dates and times are stored internally as different parts of a real number.

The value to the left of the decimal represents a date between December 30, 1899 and December 30, 9999, inclusive.  Negative values represent dates prior to December 30, 1899.

The value to the right of the decimal represents a time between 0:00:00 and 23:59:59, inclusive.  Midday is represented by .5.


DDL (Data Definition Language) <definition>
DDL (Data Definition Language)

The language used to describe attributes of a database, especially tables, fields, indexes, and storage strategy.


default workspace <definition>
default workspace

The Workspace object that the Microsoft Jet database engine automatically establishes when your application first references any data access object.  This Workspace is referenced by DBEngine.Workspaces(0) or simply Workspaces(0).


delete query <definition>
delete query

An action query that deletes a set of rows that match the criteria you specify.  A delete query doesn’t return rows.


design time <definition>
design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on.  In contrast, during run time, you interact with the application as a user would.


Double data type <definition>
Double data type

A fundamental data type that holds double-precision floating-point numbers in IEEE format.  A Double variable is stored as a 64-bit (8-byte) number ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values, from 4.94065645841247E-324 to 1.797693134862325E308 for positive values, and 0.  The type-declaration character is #.


domain <definition>
domain

A set of records defined by a table, query, or SQL expression. Aggregate functions, such as Max and StDev, return statistical information about a specific domain.


dynamic-link library (DLL) <definition>
dynamic-link library (DLL)

A library of routines loaded and linked into applications at run time.  DLLs are created with other programming languages such as C, MASM, or FORTRAN.


dynaset <definition>
dynaset

A type of Recordset object that returns a dynamic set of pointers to live database data.  Like a table- or a snapshot-type Recordset, a dynaset returns data in records (rows) and fields (columns).  Unlike a table-type Recordset, a dynaset-type Recordset can be the result of a query that joins two or more tables.  The records in dynaset-type Recordset objects are updatable if their Updatable property is True, the Field being changed is updatable, and the data page containing the current record isn’t locked.


equi-join <definition>
equi-join

A join in which records from two tables are combined and added to the Recordset object only when there are equal values in the joined fields.  In Visual Basic, equi-joins are referred to as inner joins.


expression  <definition>
expression

Any combination of operators, constants, literal values, functions, and names of fields, controls, and properties that evaluates to a single value.  You can use expressions as settings for many properties and action arguments, to set criteria, or define calculated fields in queries.


external table <definition>
external table

A table in a database outside the open Microsoft Jet database.  An external table may take the form of another file or it may be a table in another relational database.


exclusive <definition>
exclusive

Indicates whether a database or a table can be shared by other users in a multiuser environment.  If the database or table is opened for exclusive use, it can’t be shared by other users.


external database <definition>
external database

Either an ODBC database such as SQL Server that resides on a remote server, or one of the external databases such as Paradox, dBASE, FoxPro, Microsoft Excel, or Microsoft Access.


field <definition>
field

A category of information stored in a table in a database [image] a column of data.  An element of a database table that contains a specific item of information, such as last name.


field data types <definition>
field data types

The following table lists the field data types and their equivalent Visual Basic data types.

Field data type	Visual Basic data type

Boolean	Boolean

Byte	Byte

Integer	Integer

Long	Long

Currency	Double

Single	Single

Double	Double

Date/Time	Variant

Text	String

Long Binary	String or Variant; can be up to 1.2 gigabytes.

Memo	String or Variant; can be up to 1.2 gigabytes.

Note that any kind of value can be stored in a Variant data type.


field properties <definition>
field properties

Attributes of a field that determine what kind of data it contains.  Size and Type are examples.


filter <definition>
filter

A set of criteria applied to records in order to create a subset of the records.


foreign key <definition>
foreign key

One or more table fields that refer to the primary key field or fields in another table.  For example, a list of valid part numbers would contain a foreign key to an inventory table containing references to valid part numbers.  Used when establishing referential integrity for a database.


foreign table <definition>
foreign table

A database table used to contain foreign keys.  Generally, you use a foreign table to establish or enforce referential integrity.  The foreign table is usually on the many side of a one-to-many relationship.  An example of a foreign table is a table of state codes or customer orders.


form <definition>
form

A window or dialog box.  Forms are containers for controls.  A multiple-document interface (MDI) form can also act as a container for child forms and some controls.


forward scroll <definition>
forward scroll

Move toward the end (EOF) of a Recordset object.


forward-only scrolling snapshot <definition>
forward-only scrolling snapshot

A snapshot-type Recordset object in which records can be searched only from beginning to end; the current record position can't be moved back to the first record.  Forward-scrolling snapshots reduce processing overhead on remote databases. For example, you can use a forward-only snapshot on an attached remote table to quickly process data in one pass, such as when you’re building a customized report.


FROM clause <definition>
FROM clause

The part of an SQL statement that indicates the location of the data to be examined by the query by specifying which database tables are to be included in the search for the data you want.  The location specified by a FROM clause is sometimes called the domain.


Function procedure <definition>
Function procedure

A procedure that performs a specific task within a Visual Basic program and returns a value.  A Function procedure begins with a Function statement and ends with an End Function statement.


group <definition>
group

A collection of user accounts in a Workgroup object, identified by group name and personal identifier (PID).  Permissions assigned to a group apply to all users in the group.


GUID data type <definition>
GUID data type

Globally Unique Identifier/Universally Unique Identifier.  A unique identification string used with remote procedure calls. Every interface and object class uses a GUID for identification. A GUID is a 128-bit value. For example 12345678-1234-1234-1234-123456789ABC is a syntactically correct GUID. The GUIDs on the client and server must match for the client and server to bind. Vendors of OLE objects can request that Microsoft allocate one or more sets of 256 GUIDs for their exclusive use. Alternatively, if you have a network card, you can run a tool named UUIDGEN.EXE, which provides a set of 256 GUIDs based on the time of day, the date, and a unique number contained in your network card.


identifier <definition>
identifier

An element of an expression that refers to the value of a field or property.


inconsistent <definition>
inconsistent

The state of a multiple-table Recordset object that enables you to update all fields (columns).  For example, in a Recordset created by joining two tables in a one-to-many join (as in a Customers and Orders table), you can update Orders.CustomerID so that it doesn’t match Customers.CustomerID.


index  <definition>
index

A dynamic cross-reference of one or more table data fields (columns) that permits faster retrieval of specific records from a table.  As records are added, changed, or deleted, the database management system automatically updates the index to reflect the changes.

When used with a table-type Recordset object, the current index determines the order in which data records are returned to the Recordset.  A table may have several indexes defined for its data.

A data access object that represents an index for a TableDef object.


index specification

See pseudo index.


initialization file <definition>
initialization file

An ASCII text file used to contain parameters for configuring Windows-based applications, the Microsoft Jet database engine, or Microsoft Windows itself.  Generally, an initialization file uses the extension .INI and is named after the executable program that uses it.  For example, a program named TESTING.EXE would expect an initialization file called TESTING.INI.


inner join <definition>
inner join

A join in which records from two tables are combined and added to a Recordset only if the values of the joined fields meet a specified condition.  For instance, an equi-join is an inner join in which the values of the joined fields must be equal.


installable ISAM <definition>
installable ISAM

A driver you can specify that allows access to external database formats such as dBASE, Microsoft Excel, and Paradox.  ISAM is an acronym for Indexed Sequential Access Method.  The Microsoft Jet database engine installs (loads) these ISAM drivers when referenced by your application.  The location of these drivers is maintained in the Microsoft Windows registration database.


instance <definition>
instance

Any one of a set of objects sharing the same class.  For example, multiple instances of a Form class share the same code and are loaded with the same controls with which the Form class was designed.  During run time, the individual properties of controls on each instance can be set to different values.


Integer data type <definition>
Integer data type

A fundamental data type that holds integer numbers.  An Integer variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.  The type-declaration character is % (ANSI character 37).


intrinsic constant <definition>
intrinsic constant

A constant provided by an application.  For example, Visual Basic constants are listed in the Visual Basic (VB) object library and can be viewed using the Object Browser.


join <definition>
join

A database operation that combines some or all records from two or more tables, such as an equi-join, outer join, or self-join. Generally, a join refers to an association between a field in one table and a field of the same data type in another table.  You create a join with an SQL statement.

When you define a relationship between two tables, you create a join by specifying the primary and foreign table fields.  When you add a table to a query, you need to create a join between appropriate fields in the SQL statement that defines the query.


left outer join <definition>
left outer join

An outer join in which all the records from the left-hand side of the LEFT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the right-hand table.  Records from the right-hand table are combined with those from the left-hand table only when there are matching values in the joined fields.  When a left-side record has no match, a row of NULL values is joined on the right side.


left join <definition>
left join

A left outer join includes all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table.


Legend

 Applies only to object.

 Applies only to collection.

 Applies to both object and collection.


linked object <definition>
linked object

An object that is created in another application and linked to a Visual Basic application.  When you link an object, you insert a placeholder in your application.  Unlike an embedded object, a linked object's data is actually stored in and managed by the application that created it.


linked table <definition>
linked table

See attached table.


locked <definition>
locked

The condition of a data page, Recordset object, or Database object that makes it read-only to all users except the one who is currently entering data in it.


Long Binary <definition>
Long Binary

A fundamental data type that holds long-integer values.  A Long variable is stored as a 32-bit (4-byte) number ranging in value from -2,147,483,648 to 2,147,483,647.  The type-declaration character is & (ANSI character 38).


Long data type <definition>
Long data type

A four-byte integer (a whole number between -2,147,483,648 and 2,147,483,647, inclusive).


make table query <definition>
make table query

An action query that creates a new table from the Recordset object of an existing query.


many-only table <definition>
many-only table

A table that doesn’t appear as the "one" side of any join in a query.


Memo object <definition>
Memo object

An object you can use to hold the contents of a table field that has a Memo field data type.  Memo objects can contain up to 1.2GB of data.


Memo data type <definition>
Memo data type

A field data type.  Such fields can contain up to1.2GB of data.


message <definition>
message

A packet of information passed from one application to another.


method <definition>
method

A reserved word similar to a statement or function that operates on specific objects.


Microsoft Jet database engine <definition>
Microsoft Jet database engine

A database management system that retrieves data from and stores data in user and system databases.  The Jet engine can be thought of as a data manager component with which other data access systems, such as Microsoft Access and Visual Basic, are built.


multiuser database <definition>
multiuser database

A database that permits more than one user to access and modify the same set of data at the same time.  In some cases, the additional "user" may be another instance of your application or another application running on your system that accesses the same data as some other application.


normalize <definition>
normalize

To minimize the duplication of information in a relational database through effective table design.


Null <definition>
Null

A value that indicates missing or unknown data.  Null values can be entered in fields for which information is unknown and in expressions and queries.  In Visual Basic, the Null keyword indicates a Null value.  Some fields, such as those defined as containing the primary key, can’t contain null values.


null field <definition>
null field

A field containing no characters or values.  A null field isn't the same as a zero-length string ("") or a field with a value of 0.  A field is set to null when the content of the field is unknown.  For example, a Date Completed field in a task table would be left null until a task is completed.


Null propagation <definition>
Null propagation

The ability of Null expressions, when used with most operators, to take precedence over other values in expressions.


numeric expression <definition>
numeric expression

Any expression that can be evaluated as a number.  Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number.


Object Browser <definition>
Object Browser

A dialog box you can use to examine the contents of an object library to get information about the objects provided.


object data type <definition>
object data type

A collective term for objects defined by Visual Basic or by the Microsoft Jet database engine.  An object data type may represent objects that are stored in a field in the database, for example.   Object data types include any of the OLE data types or other long binary fields.


object expression <definition>
object expression

An expression that specifies a particular object.  This expression can include any of the object's containers.  For example, if your application has an Application object that contains a Document object that contains a Text object, the following are valid object expressions:

Application.Document.Text

Application.Text

Document.Text

Text


object library <definition>
object library

A file with the .OLB extension that provides information to OLE Automation controllers (like Visual Basic) about available OLE Automation objects.  You can use the Object Browser to examine the contents of an object library to get information about the objects provided.


object variable <definition>
object variable

A variable that contains a reference to an object.


ODBC (Open Database Connectivity) <definition>
ODBC (Open Database Connectivity)

A standard protocol that permits applications to connect to a variety of external database servers or files.  ODBC drivers used by the Microsoft Jet database engine permit access to Microsoft SQL Server and several other external databases.

The ODBC applications programming interface (API) may also be used to access ODBC drivers and the databases they connect to without using the Jet engine.


ODBC data source <definition>
ODBC data source

A term used to refer to a database or database server used as a source of data. ODBC data sources are referred to by their Data Source Name.  Data sources can be created using the Windows control panel or the RegisterDatabase method.


ODBC driver <definition>
ODBC driver

A dynamic-link library (DLL) used to connect a specific Open Database Connectivity data source with another (client) application.


OLE <definition>
OLE

Object linking and embedding: The technology that enables you to create applications that contain components from various other applications.


OLE Automation object <definition>
OLE Automation object

An object in an application that can be accessed and manipulated by another application, provided both applications support OLE version 2.0.  For example, Microsoft Access can create and manipulate OLE Automation objects within Microsoft Word or Microsoft Excel.


OLE Object data type <definition>
OLE Object data type

A field data type you use for objects created in other applications that can be linked or embedded in a Microsoft Jet database.


one-to-many relationship <definition>
one-to-many relationship

An association between two tables in which:

·	The primary key value of each record in the primary table corresponds to the value in the matching field or fields of a number of records (or no record) in the related table.

·	The primary key value of each record in the related table is null or corresponds to the value in the matching field or fields of one and only one record in the primary table.


one-to-one relationship <definition>
one-to-one relationship

An association between two tables in which:

·	The primary key value of each record in the primary table corresponds to the value in the matching field or fields of no more than one record in the related table.

·	The primary key value of each record in the related table is null or corresponds to the value in the matching field of one and only one record in the primary table.


optimistic <definition>
optimistic

A type of locking in which the data page containing one or more records, including the record being edited, is unavailable to other users only while the record is being updated by the Update method, but is available between the Edit and Update methods.  Optimistic locking is used when accessing ODBC databases or when the LockEdits property of the Recordset object is set to False.


outer join <definition>
outer join

A join in which all the records from one table are added to the Recordset object, even if there are no matching values in the joined field from the second table.  Records from the second table are combined with those from the first table only when there are matching values in the joined fields.  Null records are joined when there is no match.


page <definition>
page

A portion of the database in which record data is stored.  Depending on the size of the records, a page may contain more than one record.  In Microsoft Jet databases (.mdb), a page is 2048 (2K) bytes in length.


parameter <definition>
parameter

An element containing a value that you can change to affect the results of the query.  For example, a query returning data about an employee might have a parameter for the employee's name.  You can then use one QueryDef object to find data about any employee by setting the parameter to a specific name before running the query.


parameter query <definition>
parameter query

A query that requires you to provide one or more criteria values, such as Redmond for City, before the query is run.  A parameter query isn’t, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries.


parse <definition>
parse

To identify the parts of a statement or expression and then validate those parts against the appropriate language rules.


pass-through query <definition>
pass-through query

An SQL-specific query you use to send commands directly to an SQL database server (such as Microsoft SQL Server).  With pass-through queries, you work with the tables on the server instead of attaching them.  Pass-through queries are used to execute SQL queries and system-specific commands written using SQL dialects known only to the server.

A pass-through query may or may not return records.  If it does, they are always returned in a snapshot.


permission <definition>
permission

One or more attributes that specify what kind of access a user has to data or objects in a database.  For example, a table or query with Read Data permission permits a user to retrieve but not edit data in the table or query.


persistent object <definition>
persistent object

An object stored in the database; for example, a database table or QueryDef object.  Dynaset-type or snapshot-type Recordset objects are not considered persistent objects because they are created in memory as needed.


personal identifier (PID) <definition>
personal identifier (PID)

A case-sensitive alphanumeric string 4-20 characters long that the Microsoft Jet database engine uses in combination with the account name to identify a user or group in a Workgroup object.  You provide the PID and the account name when you create a new user or group.


pessimistic <definition>
pessimistic

A type of locking in which the page containing one or more records, including the record being edited, is unavailable to other users when you use the Edit method and remains unavailable until you use the Update method.  Pessimistic locking is enabled when the Lockedits property of the Recordset object is set to True.


primary key <definition>
primary key

One or more fields whose value or values uniquely identify each record in a table.  You can have only one primary key.  An Employees table, for example, could use the social security number for the primary key.


primary table <definition>
primary table

A database table used to contain primary keys.  Generally, a primary key table is used to establish or enforce referential integrity.  The primary table is usually on the one side of a one-to-many relationship with a foreign table.


property <definition>
property

A named attribute of an object.  Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.


pseudo index <definition>
pseudo index

A dynamic cross-reference of one or more table data fields (columns) that permits an ODBC table (server table) without a unique index to be edited. A pseudo index is not an actual index on the server table, but a cross-reference that the Microsoft Jet database engine can use to support table updates. A pseudo index is necessary only if an ODBC table doesn’t have a unique index, which allows the table to be updated. You don’t need a pseudo index if the table already has a unique index or if there is no need to update the table. (Tables cannot have a unique index if they were intended to be read-only.) In previous versions, pseudo indexes were called index specifications.


query <definition>
query

A formalized instruction to a database to either return a set of records or perform a specified action on a set of records as specified in the query.  For example, the following SQL query statement returns records:

SELECT CompanyName FROM Publishers WHERE State = 'NY'

You can create and run select, action, crosstab, parameter, and SQL-specific queries:


query parameter data types <definition>
query parameter data types

The set of data types for a field in a parameter query.  The Microsoft Jet database engine has 13 query parameter data types:

Category	Data type

Table fields	Currency, Date/Time, Memo, OLE Object, Text, and Yes/No correspond to the same data types in table fields.

Number	Byte, Single, Double, Integer, and Long Integer correspond to the five Field Size options of the Number data type in table fields.

Generic 	Value is a Generic data type that doesn't accept any type of data.

Binary	You can use the Binary data type in parameter queries directed to attached tables that recognize it.


QueryDef object <definition>
QueryDef object

A data access object that contains the SQL statement that describes a query and its properties, such as DateCreated and ODBCTimeout.  Querydef objects with an ODBC Connect property may contain an SQL statement that can only be executed on an external database like Microsoft SQL Server.  This is called an SQL pass-through query.


read-only <definition>
read-only

A type of access to data whereby information can be retrieved but not modified.


record <definition>
record

A set of related data about a person, place, event, or some other item.  Table data is stored in records (rows) in the database.  Each record is composed of a set of related fields (columns) [image] each field defining one attribute of information for the record.  Taken together, a record defines one specific unit of retrievable information in a database.


recordset <definition>
recordset

A logical set of records.  The three types of Recordset objects are dynaset, snapshot, and table.


recordset population <definition>
recordset population

The process of loading Recordset records into memory.

When a dynaset- or snapshot-type Recordset is first opened, it usually contains only one record, even if the query returns additional records.  As your code moves the current record forward (toward EOF) through the Recordset, additional records are fetched and become members of either the keyset (dynaset) or the set of records in memory (snapshot).  This process is called recordset population.  Executing the MoveLast or FindLast methods or setting the PercentPosition property to 100 completely populates the Recordset.

In Visual Basic version 4.0, when using SQL Passthrough against ODBC data sources, the Recordset isn’t fully populated when first opened (as it was in Visual Basic version 3.0).


referential integrity <definition>
referential integrity

Rules that you set to establish and preserve relationships between tables when you add, change, or delete records.  Enforcing referential integrity prohibits users from adding records to a related table for which there is no primary key, changing values in a primary table that would result in orphaned records in a related table, and deleting records from a primary table when there are matching related records.

If you select the Cascade Update Related Fields or Cascade Delete Related Records option for a relationship, the Microsoft Jet database engine allows changes and deletions but changes or deletes related records to make sure the rules are still enforced.


relationship <definition>
relationship

An association established between common fields (columns) in two tables.  A relationship can be one-to-one or one-to-many.


requery <definition>
requery

To rerun a query to reflect changes to the records, retrieve newly added records, and eliminate deleted records.


reserved word <definition>
reserved word

A word that is part of a language, such as the Microsoft Jet database engine SQL language.  Reserved words include the names of statements, predefined functions and data types, methods, operators, and objects.  Examples include SELECT, UPDATE, BETWEEN, SET and INSERT.  Don’t use reserved words for variable or object names.


right join <definition>
right join

A right outer join includes all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table.

For example, you could use LEFT JOIN with the Departments (left) and Employees (right) tables to select all departments, including those that have no employees assigned to them.  To select all employees, including those who aren't assigned to a department, you would use RIGHT JOIN.


right outer join <definition>
right outer join

An outer join in which all the records from the right side of the RIGHT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the left table.  Records from the left table are combined with those from the right table only when there are matching values in the joined fields.


row <definition>
row

A set of related columns or fields used to hold data.  A row is synonymous with a record in the Microsoft Jet database engine.  A table is composed of zero or more rows of data.


run time <definition>
run time

The time when code is running.  During run time, you interact with the code as a user would.


run-time error <definition>
run-time error

An error that occurs when code is running.  A run-time error results when a statement attempts an invalid operation.


scope <definition>
scope

The attribute of a variable or procedure that determines which sections of which modules recognize it.  There are three levels of scope: global, module, and procedure.  Variables that you declare globally can be accessed by any module, while variables that you declare in a specific module can be used only within that module.  Also, variables that you declare in a Sub or Function procedure can be used only in that particular procedure.


secure workgroup <definition>
secure workgroup

A Microsoft Jet database Workgroup object to which users log on with a user name and password and in which access to database objects is restricted according to permissions specified for user accounts and groups.


security <definition>
security

A set of features used to specify or restrict the access that specified users or user groups have to data and objects in a database.


select query <definition>
select query

A query that asks a question about the data stored in your tables and returns a Recordset object without changing the data.  Once the Recordset data is retrieved, you can examine and make changes to the data in the underlying tables.  In contrast, action queries can make changes to your data, but they don't return data records.


self-join <definition>
self-join

A join in which records from a table are combined with other records for the same table where there are matching values in the joined fields.  A self-join can be an equi-join or an outer join.  A self-join is useful when you ask hierarchical questions, such as a query that shows all the managers and the people who report to them.


server <definition>
server

The database management system designed to share data with client applications; servers and clients are often connected over a network.  A database server usually contains and manages a central repository of data that remote client applications can retrieve and manipulate.


session <definition>
session

A session delineates a sequence of operations performed by the Microsoft Jet database engine.  A session begins when a user logs in and ends when a user logs off.  All operations performed during a session form one transaction scope and are subject to permissions determined by the login user name and password.  Sessions are implemented as Workspace objects by the Jet engine.


Short data type <definition>
Short data type

A Microsoft Jet database engine fundamental data type that corresponds to the Integer data type defined by Visual Basic for Applications.  A Short variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.  The type-declaration character is % (ANSI character 37).


Single data type <definition>
Single data type

A fundamental data type that holds single-precision floating-point numbers in IEEE format.  A Single variable is stored as a 32-bit (4-byte) number ranging in value from -3.402823E38 to -1.401298E-45 for negative values, from 1.401298E-45 to 3.402823E38 for positive values, and 0.  The type-declaration character is ! (ANSI character 33).


snapshot <definition>
snapshot

A static copy of a set of records retrieved from the database and copied into memory.  Snapshot-type Recordset objects can be created from a base table, a query, or another recordset.  Snapshots are not updatable.  All SQL pass-through queries return snapshots.


sort order <definition>
sort order

A sequencing principle used to order data; for example, alphabetic, numeric, ascending, descending, and so on.


SQL database <definition>
SQL database

A database that can be accessed through use of Open Database Connectivity (ODBC) data sources.


SQL-specific query <definition>
SQL-specific query

A query that can be created only by writing an SQL statement.  Subqueries and pass-through, union, and data-definition queries are SQL-specific queries.


SQL statement/string <definition>
SQL statement/string

An expression that defines a Structured Query Language (SQL) command, such as SELECT, UPDATE, or DELETE, and includes clauses such as WHERE and ORDER BY.  SQL strings and statements are typically used in queries, Recordset objects, and aggregate functions but can also be used to create or modify a database structure.


standard deviation <definition>
standard deviation

A parameter that indicates the way in which a probability function is centered around its mean and that is equal to the square root of the moment in which the deviation from the mean is squared.  Used to describe sets of values to determine how far the value varies from the arithmetic mean or average.


standard naming conventions <definition>
standard naming conventions

A set of specific rules for naming Microsoft Jet database engine objects.  Names can be up to 64-characters long and can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation mark (!), a backquote character (`), and brackets ([ ]).  You also can't use leading spaces or control characters (ASCII values 0 through 31).


string comparison <definition>
string comparison

The use of an operator to determine whether one string is greater than or equal to another string.  If you use Option Compare Text in the Declarations section of a module, string comparisons are not case-sensitive.  If you use Option Compare Binary, comparisons are case-sensitive.  If you use Option Compare Database, the comparison method is set by the current database.


String data type <definition>
String data type

A fundamental data type that holds character information.  A String variable can contain approximately 65,535 bytes (64K), is either fixed-length or variable-length, and contains one character per byte.  Fixed-length strings are declared to be a specific length.  Variable-length strings can be any length up to 64K, less a small amount of storage overhead.

The type-declaration character for the String data type is $.


string expression <definition>
string expression

Any expression that evaluates to a sequence of contiguous characters.  Elements of the expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).


Structured Query Language (SQL) <definition>
Structured Query Language (SQL)

A language used in querying, updating, and managing relational databases.  SQL can be used to retrieve, sort, and filter specific data to be extracted from the database.

You can use SQL SELECT statements anywhere a table name, query name, or field name is accepted.  For example, you can use an SQL statement in place of a table name in the OpenRecordset method.


syntax error <definition>
syntax error

An error that occurs when you enter a line of code that Visual Basic doesn't recognize.

Note   Syntax rules for individual keywords are defined in the Syntax section of the associated Help topic.  To get Help on a keyword from within the development environment, select the keyword and press F1.


system object <definition>
system object

A database object defined by the Microsoft Jet database engine, such as the table MSysIndexes.


table <definition>
table

The basic unit of data storage in a relational database.  A table stores data in records (rows) and fields (columns) and is usually about a particular category of things, such as employees or parts. Also called a base table.

A table-type Recordset is a logical representation of a base table in a database.


TableDef object <definition>
TableDef object

An object in a database that defines the structure of a table.  In contrast, a table is the physical container of the data in a database.


temporary disk <definition>
temporary disk

The disk or directory, identified by the TEMP operating system environment variable, where the Microsoft Jet database engine stores temporary files and result sets.  Also known as a temporary drive.  Although the TEMP environment variable can point to a RAM disk, this isn’t recommended.


TEMP <definition>
TEMP

A TEMP environment variable is set by your AUTOEXEC.BAT file when you start your system.  Generally, TEMP points to an area on your hard disk used by Microsoft Windows and other programs, like the Microsoft Jet database engine, to store information that doesn't need to be saved after you shut down your system.  For example, the following line in your AUTOEXEC.BAT file points the TEMP environment variable to the D:\TEMPAREA directory:

SET TEMP=D:\TEMPAREA


Text data type <definition>
Text data type

A field data type.  Text fields can contain up to 255 characters or the number of characters specified by the Size property of the Field object, whichever is less.


transaction <definition>
transaction

A series of changes made to a database's data and schema.  Mark the beginning of a transaction with the BeginTrans statement, commit the transaction using the CommitTrans statement, and undo all your changes since BeginTrans using the Rollback statement.

There is an implicit transaction while action queries are running.  If a query doesn’t complete for any reason, it is automatically rolled back.

Transactions are optional and can be nested up to five levels.  Transactions increase the speed of data changing operations and enable changes to be reversed easily.

Transactions are global to the referenced database object's Workspace.


two's complement <definition>
two's complement

A type of base-2 notation used to represent positive and negative in which negative values are formed by complementing all bits and adding 1 to the result.  Complementing is done by changing all 1s to 0, and all 0s to 1.


union query <definition>
union query

A SQL-specific select query that creates a snapshot-type Recordset object containing data from all specified records in two or more tables with any duplicate records removed.  To include the duplicates, add the keyword ALL.

For instance, a union query of the Customers table and the Suppliers table results in a snapshot-type Recordset that contains all suppliers that are also customers.


update <definition>
update

The process that saves changes to data in a record.  Until the record is saved, changes are stored in a temporary record called the copy buffer.  The UPDATE clause in an SQL Statement changes data values in one or more records (rows) in a database table.


update query <definition>
update query

An action query that changes a set of records according to criteria you specify.  An update query doesn’t return any records.


user account <definition>
user account

An account identified by a user name and personal identifier (PID) that is created to manage access to database objects in a Microsoft Jet database Workgroup object.


validation <definition>
validation

The process of checking whether entered data meets certain conditions or limitations.


validation properties <definition>
validation properties

Properties used to set conditions on table fields and records.  Validation properties include ValidationRule, Required, and AllowZeroLength.


validation rule <definition>
validation rule

A rule that sets limits or conditions on what can be entered in one or more fields.  Validation rules can be set for a Field or a TableDef object.  Validation rules are checked when you update a record containing fields requiring validation.  If the rule is violated, a trappable error results.


variable <definition>
variable

A named storage location that can contain data that can be modified during program execution.  Each variable has a name that uniquely identifies it within its level of scope.  A data type can be specified or not.

Variable names:

Must begin with an alphabetic character.

Can't contain an embedded period or type-declaration character.

Must be unique within the same scope.

Must be no longer than 255 characters.


Variant data type <definition>
Variant data type

A special data type that can contain numeric, string, or date data as well as the special values Empty and Null.  The VarType function defines how the data in a Variant is treated.  All variables become variant types if not explicitly declared as some other type.


variant expression <definition>
variant expression

Any expression that can evaluate to numeric, string, or date data as well as the special values Empty and Null.


VarType <definition>
VarType

The VarType function returns a value that provides information about the type of data stored in a variable.  The following table shows the equivalent constant, the return value, and a description of the variable:

Constant	Value	Description

vbEmpty	0	Uninitialized

vbNull	1	Contains no valid data

vbInteger	2	Integer

vbLong	3	Long integer

vbSingle	4	Single-precision floating-point number

vbDouble	5	Double-precision floating-point number

vbCurrency	6	Currency

vbDate	7	Date

vbString	8	String

vbObject	9	OLE Automation object

vbError	10	Error

vbBoolean	11	Boolean

vbVariant	12	Variant (used only for arrays of Variants)

vbDataObject	13	Non-OLE Automation object

vbByte	17	Byte

vbArray	8192	Array

Note   The constant vbArray combined with any other constant indicates an array of that type of variable.


WHERE clause <definition>
WHERE clause

The part of an SQL statement that specifies which records to retrieve.  The WHERE clause limits the scope of the query and specifies which columns are used to join multiple tables.  When using the Microsoft Jet database engine to perform the query, use the JOIN clause to join multiple tables.


wildcard characters <definition>
wildcard characters

The asterisk (*), question mark (?), number sign (#), exclamation point (!), hyphen (-), and brackets ([ ]) are wildcard characters.  You can use these characters in queries and expressions to include all records, filenames, or other items that begin with specific characters or match a certain pattern.  You can also use wildcard characters and matching characters to further refine a search when using an SQL statement.

Symbol	Example	Usage
*	wh* finds what, white, and why *at finds cat, bat, and what	Like the MS-DOS asterisk (*) wildcard character, this asterisk matches any number of characters.  But unlike MS-DOS, it can be used anywhere in the character string.
?	b?ll finds ball, bell, and bill	Like the MS-DOS ? wildcard character, this symbol matches any single character.
#	1#3 finds 103, 113, 123	Matches any single digit.
[ ]	b[ae]ll finds ball and bell but not bill	Matches any single character within the brackets.
!	b[!ae]ll finds bill and bull but not bell or ball	Matches any character not in the list.
-	b[a-c]d finds bad, bbd, and bcd	Matches any one of a range of characters.
Note   The wildcard characters * (asterisk), ? (question mark), # (number sign), and [ (opening bracket) can match themselves only if enclosed in brackets.


workgroup <definition>
workgroup

A group of users in a multiuser environment who share data and the same system database (typically the SYSTEM.mdw file).


workgroup administrator <definition>
workgroup administrator

A member of the group Admins in a Microsoft Jet database Workgroup object.  A workgroup administrator can always obtain full permissions for any database object created in the Workgroup.


workspace <definition>
workspace

A Workspace object defines a session for a specific user.  When Visual Basic starts, a default Workspace is created with a password of "" and username of "Admin".


Yes/No data type <definition>
Yes/No data type

A field data type that contains a Boolean (True/False or yes/no) value.


zero-length string <definition>
zero-length string

A string containing no characters.  The Len function of a zero-length string returns 0.


Data Access Methods Reference

This reference groups all data-access methods by object or collection and lists them alphabetically.

Grouped by Object

Container Database DBEngine Document Error Field Group Index	Parameter Property QueryDef Recordset Relation TableDef User Workspace
Listed Alphabetically

A-B

AddNew Append	AppendChunk BeginTrans
C

CancelUpdate Clone Close CommitTrans CompactDatabase CopyQueryDef CreateDatabase CreateField	CreateGroup CreateIndex CreateProperty CreateQueryDef CreateRelation CreateTableDef CreateUser CreateWorkspace
D-F

Delete Edit Execute FieldSize FillCache	FindFirst FindLast FindNext FindPrevious
G-M

GetChunk GetRows Idle MakeReplica Move	MoveFirst MoveLast MoveNext MovePrevious
N-Z

NewPassword OpenDatabase OpenRecordset Refresh RefreshLink RegisterDatabase	RepairDatabase Requery Rollback Seek Synchronize Update


Data Access Object Hierarchy


Data Access Objects and Collections Reference

Data access objects and collections provide a framework for using code to create and manipulate components of your database system. Objects and collections have properties that describe the characteristics of database components and methods that you use to manipulate them. Together these objects and collections form a hierarchical model of your database structure, which you can control programmatically.

Objects and collections provide different types of containment relations: Objects contain zero or more collections, all of different types; and collections contain zero or more objects, all of the same type. Although objects and collections are similar entities, the distinction differentiates the two types of relations.

In the following table, the type of collection in the first column contains the type of object in the second column. The third column describes what each type of object represents.

Collection	Object	Description

Containers	Container	Storage for information about a predefined object type

Databases	Database	An open database

None	DBEngine	The Microsoft Jet database engine

Documents	Document	Information about a saved, predefined object

Errors	Error	Information about any errors associated with this object

Fields	Field	A column that is part of a table, query, index, relation, or recordset

Groups	Group	A group of user accounts

Indexes	Index	Predefined ordering and uniqueness of values in a table

Parameters	Parameter	A parameter for a parameter query

Properties	Property	A built-in or user-defined property

QueryDefs	QueryDef	A saved query definition

Recordsets	Recordset	The records in a base table or query

Relations	Relation	A relationship between fields in tables and queries

TableDefs	TableDef	A saved table definition

Users	User	A user account

Workspaces	Workspace	A session of the Jet database engine


Data Access Properties Reference

This reference groups all data-access properties by object or collection and lists them alphabetically.

Grouped by Object

Container Database DBEngine Document Error Field Group Index	Parameter Property QueryDef Recordset Relation TableDef User Workspace

Listed Alphabetically

A-B

AbsolutePosition AllowZeroLength AllPermissions Attributes	BOF Bookmark Bookmarkable

C

CacheSize CacheStart Clustered CollatingOrder	ConflictTable Connect Count

D-E

DataUpdatable DateCreated DefaultUser DefaultPassword DefaultValue	Description DistinctCount EditMode EOF

F-I

Filter Foreign ForeignName ForeignTable HelpContext HelpFile	IgnoreNulls Index Inherit Inherited IniPath IsolateODBCTrans

L-O

LastModified LastUpdated LockEdits LoginTimeout LogMessages Name	NoMatch Number ODBCTimeout OrdinalPosition Owner

P-R

Password PercentPosition Permissions PID Primary QueryTimeout	RecordCount RecordsAffected Required Restartable ReturnsRecords

S

Size Sort Source SourceField	SourceTable SourceTableName SQL

T-Z

Table Transactions Type Unique Updatable UserName	V1xNullBehavior ValidateOnSet ValidationRule ValidationText Value Version


Using Data Access

The following topics can provide additional detailed information on specific subjects.

Data Access Objects Overview

Accessing Data in ODBC Databases with DAO

Accessing Databases on CD-ROM with DAO

Accessing External Databases with DAO

Building SQL Statements in Code

Choosing a Field Data Type with DAO

Creating a Database with DAO

Creating Parameter Queries with DAO

Customizing Windows Registry Settings for Data Access Objects

Initializing the Microsoft ODBC Database Driver

Locking Behavior in Multiuser Applications

Populating Recordsets and Counting Records with DAO

Positioning the Current Record Pointer with DAO

Querying a Database with SQL in Code

Retrieving Data Using SQL and DAO

Selecting a Recordset Type for Data Access Objects

Using Counter Fields with DAO

Using Named Arguments

Using SQL PassThrough with DAO

Using the MSysConf Table to Administer SQL Database Access through DAO


Container Object

A Container object groups similar types of Document objects together [image] for example, one container might have Tables documents. Applications can define their own document types and corresponding containers.

Remarks

Each Database object has a Containers collection consisting of built-in Container objects. Some of these Container objects are defined by the Microsoft Jet database engine while others may be defined by other applications. The following table lists the name of each Container object defined by the Jet database engine and what type of information it contains.

Container name	Contains information about

Databases	Containing database

Tables	Saved tables and queries

Relations	Saved relationships

Note   Don't confuse the particular types of Container objects listed in the preceding table with the collection types of the same name. The Databases type of Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Each Container object has a Documents collection that contains a Document object for each instance of the type of object it describes. You typically use a Container object with one of the Document objects in the Documents collection, so you can consider a Container object to be an intermediate link to the information that the Document object contains.

Because Container objects are built-in, you can't create new Container objects or delete existing ones. Using the properties of an existing Container object, you can:

Determine the predefined names an object has by checking its Name property setting.

Determine or specify the owner of the Container object by checking or setting its Owner property. To set the Owner property, you must have write permission for the Container object, and you must set the property to the name of an existing User or Group object.

Set access permissions for the Container object using the Permissions and UserName properties; any Document object created in the Documents collection of a Container object inherits these access permission settings.

You can refer to a Container object in a collection by its ordinal number or by its Name property setting, using either of the following syntax forms:

Containers(0)

Containers(“name”)


Containers Collection

A Containers collection contains all of the Container objects that are defined in a database.

Remarks

Each Database object has a Containers collection consisting of built-in Container objects. Some of these Container objects are defined by the Microsoft Jet database engine while others may be defined by other applications.


Container Object, Containers Collection Summary

Container Object

The Container object contains no methods; it contains these collections and properties.

Collections

Documents (default)

Properties

Properties

AllPermissions

Inherit

Name

Owner

Permissions

UserName

Containers Collection

A Containers collection appears in each Database object, and contains this method and this property.

Method

Refresh

Property

Count


Database Object

A Database object represents an open database.

Remarks

You manipulate an open database using a Database object and its methods and properties. You can examine the collections in a Database object to learn about its tables, queries, and relationships. You can also use its collections to modify or create tables, queries, recordsets, and relationships. For example, you can:

Use the Execute method to run an action QueryDef object or pass an SQL string to an ODBC database.

Use the OpenRecordset method to create a new Recordset object directly from the Database object.

Use the Close method to close an open database.

You use the CreateDatabase method to create a new, persistent Database object and append it to the Databases collection, thereby saving it to disk. After you create a new database, you must create new tables to hold your data. You can also create new indexes and table relationships, attach existing external tables, or establish a protection scheme using permissions, groups, and users.

To open an existing Database object, use the OpenDatabase method, which appends the object to the Databases collection. The OpenDatabase method applies to the Workspace object. You can use the OpenDatabase method on the default Workspace(0) object, or on a different opened Workspace object.

When you use one of the transaction methods (BeginTrans, CommitTrans, or Rollback) on the Workspace object, these transactions apply to all databases opened on the Workspace from which the Database object was opened. If you want to use independent transactions, you must first open an additional Workspace object, and then open another Database object in that Workspace object. For example, to create two independent Database objects:

Dim dbsThisOne As Database, dbsThatOne As Database
Dim wspFirst As Workspace, wspSecond As Workspace

Dim strUserName As String

Set wspFirst = Workspaces(0)	' Use the default Workspace.

Set dbsThisOne = wspFirst.OpenDatabase("Biblio.mdb")

' Get UserName of default Workspace.

strUserName = wspFirst.UserName

' Create new Workspace.

Set wspSecond = DBEngine.CreateWorkspace("Special", strUserName, "SpecialPW")

Set dbsThatOne = wspSecond.OpenDatabase("Biblio.mdb")

You don’t need to specify the DBEngine object when using the OpenDatabase method. If you need to open a Database object in a separate transaction context, then you must reference a specific Workspace object. For example, the following statements are equivalent:

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

Set dbsBiblio = OpenDatabase("Biblio.mdb")

Opening a database with attached tables doesn't automatically establish links to the specified external files or external ODBC databases; either the table's TableDef or Field objects must be referenced, or a Recordset object opened on it. If links to these tables can't be established, a trappable error occurs. You may also need permission to access the database, or the database may already be open for exclusive use by another user. In these cases, trappable errors occur.

You can also open an external database (such as FoxPro, dBASE, and Paradox) directly instead of opening a Microsoft Jet database that has links to its tables. See the OpenDatabase method for more information.

For example, to open a FoxPro database, you could use the following code.

Dim dbsFoxFiles As Database

Set dbsFoxFiles = Workspaces(0).OpenDatabase("C:\FoxFiles", _

False,False,"FoxPro 2.5")

Note   Opening a Database object directly on an ODBC data source such as Microsoft SQLServer is not recommended because query performance is much slower than when using linked tables. Performance is not a problem with opening a Database object on an external ISAM database, such as FoxPro, Paradox, etc.

You use the Close method to remove a Database object from the Databases collection without deleting it from disk. Any open Recordset objects in the database are closed automatically when the Database object is closed.

When a procedure that declares a Database object completes execution, these local Database objects are closed along with any open Recordset objects. Any pending updates are lost and any pending transactions are rolled back, but no trappable error occurs. You should explicitly complete any pending transactions or edits and close Recordset objects and Database objects before exiting procedures that declare these object variables locally.

The first database opened is Databases(0). The Name property setting of a database is a string that specifies the path of the database file. The Connect property specifies the database type and any other parameters used to connect to external databases. You can refer to any Database object by its Name property setting using this syntax:

Databases(“name”)

You can also refer to the object by its ordinal number using this syntax (which refers to the first member of the Databases collection):

Databases(0)


Databases Collection

A Databases collection contains all open Database objects opened or created in a Workspace object of the Microsoft Jet database engine.

Remarks

When you open an existing Database object or create a new one from a Workspace, it is automatically appended to the Databases collection. When you close a Database object with the Close method, it is removed from the Databases collection but not deleted from disk. You should close all open Recordset objects before closing a Database object.

The first database that is opened is appended to the collection as Databases(0). The Name property setting of a database is a string that specifies the path of the database file. You can refer to any Database object in a collection by its Name property using this syntax:

Databases(“name”)

You can also refer to the object by its ordinal number using this syntax (which refers to the first member of the Databases collection):

Databases(0)


Database Object, Databases Collection Summary

Database Object

The Database object contains these collections, methods, and properties.

Collections

Containers

Properties

QueryDefs

Recordsets

Relations

TableDefs (default)

Methods

Close

CreateProperty

CreateQueryDef

CreateRelation

CreateTableDef

Execute

MakeReplica

OpenRecordset

Synchronize

Properties

CollatingOrder

Connect

Name

QueryTimeout

RecordsAffected

Transactions

Updatable

V1xNullBehavior

Version

Databases Collection

A Databases collection appears in each Workspace object, and contains this method and this property.

Method

Refresh

Property

Count


DBEngine Object

The DBEngine object represents the Microsoft Jet database engine. As the top-level object, it contains and controls all other objects in the hierarchy of data access objects.

Remarks

Use the DBEngine object to control the Jet database engine, manipulate its properties, and perform tasks on temporary objects that aren't elements of collections. For example, you can:

Use the Version property to obtain the version number of the Jet engine, the LoginTimeout property to obtain or set the ODBC login timeout, and the RegisterDatabase method to provide ODBC information to the Jet engine.

Use the Idle method to enable the Jet engine to complete any pending tasks and the CompactDatabase and RepairDatabase methods to maintain database files.

Use the CreateWorkspace method to create a new session.

Use the Errors collection to examine data access error details.

The DBEngine object is a predefined object; you can't create additional DBEngine objects. To refer to a collection that belongs to the DBEngine object, or to refer to a method or property that applies to this object, use this syntax:

[DBEngine.][collection | method | property]

The DBEngine object isn't an element of any collection.


DBEngine Object Summary

The DBEngine object contains these collections, methods, and properties.

Collections

Errors

Properties

Workspaces (default)

Methods

CompactDatabase

CreateWorkspace

Idle

RegisterDatabase

RepairDatabase

Properties

DefaultPassword

DefaultUser

IniPath

LoginTimeout

SystemDB

Version


Document Object

A Document object includes information about one instance of a type of object. The object can be a database, saved table, query, or relationship.

Remarks

Each Container object has a Documents collection containing Document objects that describe instances of built-in Container types. The following table lists the type of object each Document describes, the name of its Container object, and what type of information Document contains.

Document	Container	Contains information about

Database	Databases	Containing database

Table or query	Tables	Saved table or query

Relationship	Relations	Saved relationship

Note   Don't confuse the particular types of Container objects with the collection types of the same name. For example, the Databases Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Because a Document object corresponds to an existing object, you can't create new Document objects or delete existing ones. Using the properties of an existing Document object, you can:

Determine the name that a user or the Microsoft Jet database engine gave to the object when it was created by checking the Name property setting.

Determine or specify the owner of the object by checking or setting the Owner property. To set the Owner property, you must have write permission for the Document object, and you must set the property to the name of an existing User or Group object.

Determine the name of the Container object that contains the Document object by checking the Container property setting.

Determine or specify the access permissions of a user or group for the object by checking or setting the UserName or Permissions property. To set these properties, you must have write permission for the Document object, and you must set the UserName property to the name of an existing User or Group object.

Determine the date and time when the Document object was created and last modified by checking the DateCreated and LastUpdated property settings.

You can refer to a Document object by its Name property setting using this syntax:

cntApplication.Documents(“name”)


Documents Collection

A Documents collection contains all of the Document objects for a specific type of object.

Remarks

Each Container object has a Documents collection containing Document objects that describe instances of built-in Container types property settings.

You can refer to a Document object in a collection by its Name property setting using this syntax:

cntApplication.Documents(“name”)


Document Object, Documents Collection Summary

Document Object

The Document object contains no methods; it contains this collection and these properties.

Collection

Properties

Properties

AllPermissions

Container

DateCreated

KeepLocal

LastUpdated

Name

Owner

Permissions

Replicable

UserName

Documents Collection

A Documents collection appears in each Container object, and contains this method and this property.

Methods

Refresh

Property

Count


Dynaset-Type Recordset Object

A dynaset-type Recordset object is a type of Recordset object you can use to manipulate data in an underlying database table or tables. A dynaset-type Recordset object is a dynamic set of records that can contain fields from one or more tables or queries in a database and may be updatable.

Remarks

To create a dynaset-type Recordset object, use the OpenRecordset method on an open database, against another dynaset- or snapshot-type Recordset object, or on a QueryDef object.

A dynaset-type Recordset object is different from a snapshot-type Recordset object because only a unique key for each record is brought into memory, instead of actual data. As a result, a dynaset is normally updated with changes made to the source data, while the snapshot is not. Like the table-type Recordset object, a dynaset's current record is fetched only when its fields are referenced.

If you request a dynaset-type Recordset object and the Microsoft Jet database engine is unable to gain read-write access to the records, the Jet database engine may create a read-only, dynaset-type Recordset object. If the Recordset object created isn't updatable, its Updatable property setting is False (0).

As base table data changes due to updates made by your application or by other users, current data is available to your application when you reposition the current record. In a multiuser database, more than one user can open a dynaset-type Recordset object referring to the same records. Because a dynaset-type Recordset object is dynamic, when one user changes a record, other users have immediate access to the changed data. However, if one user adds a record, other users aren't notified until they use the Requery method on the Recordset object. If a user deletes a record, other users are notified when they try to access it.

Records added to the database don't become a part of your dynaset-type Recordset object unless you add them using the AddNew method. For example, if you use an action query containing an INSERT INTO SQL statement to add records, the new records aren't included in your dynaset-type Recordset object until you either use the Requery method or you rebuild your Recordset object using the OpenRecordset method.

To maintain data integrity, dynaset- and table-type Recordset objects are locked during Edit (pessimistic locking) and Update methods operations (optimistic locking) so that only one user can update a particular record at a time. When the Jet database engine locks a record, it locks the entire 2K page containing the record.

Optimistic and pessimistic locking are also used with non-ODBC tables. When you access external tables using ODBC you should always use optimistic locking. The locking conditions in effect during editing are determined by the LockEdits property.

Not all fields can be updated in all dynaset-type Recordset objects. To determine whether you can update a particular field, check the Updatable property setting of the Field object.

A dynaset-type Recordset object may not be updatable if:

There isn't a unique index on the ODBC or Paradox table or tables.

The data page is locked by another user.

The record has changed since you last read it.

The user doesn't have permission.

One or more of the tables or fields are set to Read-Only.

The database is opened as Read-Only.

The Recordset object was either created from multiple tables without a JOIN statement or the query was too complex.

The order of dynaset-type Recordset object or Recordset data doesn't necessarily follow any specific sequence. If you need to order your data, use an SQL statement with an ORDER BY clause to create the Recordset object. You can also use this technique to filter the records so that only certain records are added to the Recordset object. For example, the following code selects only titles that were published between 1993 and 1994 and sorts the resulting records by title.

Dim dbsBiblio As Database, rstTitles As Recordset
Dim strSelect As String

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

strSelect = "SELECT * FROM Titles  " _

& " WHERE [Year Published] BETWEEN 1993 AND 1994 " _

& " ORDER BY ISBN;"

Set rstTitles = dbsBiblio.OpenRecordset(strSelect, dbOpenDynaset)

Using this technique instead of using the Filter or Sort properties or testing each record individually generally results in faster access to your data.


Error Object

The Error object contains details about data access errors, each of which pertains to a single operation involving data access objects (DAO).

Remarks

Any operation involving data access objects can generate one or more errors. As each error occurs, one or more Error objects are placed in the Errors collection of the DBEngine object.

When another DAO operation generates an error, the Errors collection is cleared, and the new Error object is placed in the Errors collection. DAO operations that don't generate an error have no effect on the Errors collection.

Elements of the Errors collection aren't appended as they typically are with other collections. The set of Error objects in the Errors collection describes one error. The first Error object is the lowest level error, the second the next higher level, and so forth. For example, if an ODBC error occurs while trying to open a Recordset object, the last Error object contains the DAO error indicating that the object couldn't be opened. The first error object contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the driver manager, and possibly the driver itself, return separate Error objects.

Note   If you use the New keyword to create an object that subsequently causes an error before that object has been appended to a collection, the DBEngine Errors collection will not contain an entry for that object's error (because it might still contain information from a previous error).

To determine if the error information in the Errors collection is valid, compare the Number property of the first element of the Errors collection (DBEngine.Errors(0)) with the value of the Visual Basic Err object.

Error handling code should examine the Errors collection whenever you anticipate a data access error. If you are writing a centralized error handler, test the Visual Basic Err object. If it matches the Errors(0) object, you can then use a series of Select Case statements to identify the particular data access error or errors that occurred.


Errors Collection

The Errors collection contains all stored Error objects, each of which pertains to a single operation involving data access objects (DAO).

Remarks

Any operation involving data access objects can generate one or more errors. As each error occurs, one or more Error objects are placed in the Errors collection of the DBEngine object. When another DAO operation generates an error, the Errors collection is cleared, and the new Error object is placed in the Errors collection. DAO operations that don't generate an error have no effect on the Errors collection.

Elements of the Errors collection aren't appended as they typically are with other collections.

The set of Error objects in the Errors collection describes one error. The first Error object is the lowest level error, the second the next higher level, and so forth. For example, if an ODBC error occurs while trying to open a Recordset object, the last Error object contains the DAO error indicating that the object couldn't be opened. The first error object contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the driver manager, and possibly the driver itself, return separate Error objects.

Note   If you use the New keyword to create an object that causes an error either before or while being placed into the Errors collection, the collection doesn't contain error information about that object (because it might contain information from a previous error).

The error information is available in the Visual Basic Err object.


Error Object, Errors Collection Summary

Error Object

An Error object contains no methods; it contains this collection, and these properties:

Collection

Properties

Properties

Description

HelpContext

HelpFile

Number

Source

Errors Collection

The Errors collection appears in the DBEngine object, and contains this method and this property:

Method

Refresh

Property

Count


Field Object

A Field object represents a column of data with a common data type and a common set of properties.

Remarks

The Fields collections of Index, QueryDef, Relation, and TableDef objects contain the specifications for the fields those objects represent. The Fields collection of a Recordset object represents the Field objects in a row of data, or in a record. You use the Field objects in a Recordset object to read and set values for the fields in the current record of the Recordset object.

You manipulate a field using a Field object and its methods and properties. For example, you can:

Get or set the presentation order of the Field object in a Fields collection using the OrdinalPosition property.

Read the SourceField and SourceTable property settings to determine the original source of the data.

Read or set the ForeignName property setting for a field in a Relation object.

Read or set the AllowZeroLength, DefaultValue, Required, ValidateOnSet, ValidationRule, or ValidationText property setting to find or specify validation conditions.

Read or set the Value property of a Recordset object.

Use the AppendChunk, FieldSize, and GetChunk methods to get or set a value in an OLE Object or Memo field of a Recordset object.

You can refer to the Value property of a Field object that you create and append to a Fields collection by its Name property setting using following syntax:

Fields("name")

Note   Fields that have names with embedded spaces must be delimited with brackets ([ ]), for example [Part Number], or enclosed in single quotation marks (' ') or double quotation marks (" "), as in 'Part Number' or "Part Number".

You can also refer to the Value property of a Field object that you create and append to a Fields collection by Its position in the Fields collection using this syntax:

Fields(0)

To create a new Field object in an Index, TableDef, or Relation object, use the CreateField method.

When the Field object is accessed as part of a Recordset object, data from the current record is visible in the Field object's Value property. To manipulate data in the Recordset object, you don't usually reference the Fields collection directly; instead you indirectly reference the Value property of the Field object in the Fields collection of the Recordset object, as in the following example.

Dim dbsCatalog As Database, rstParts As Recordset
Dim strSelect As String

Set dbsCatalog = Workspaces(0).OpenDatabase("Catalog.mdb")
strSelect = "SELECT [Part Name], Size,  " _

& "[Part Type], [Part Age] AS Age FROM Parts"

Set rstParts = dbsCatalog.OpenRecordset(strSelect)

'Return Part Name field in Recordset object.

Debug.Print rstParts.Fields(0).Value

' Otherwise, use indirect coding.

Debug.Print rstParts(0)	' Return value of Part Name field.

Debug.Print rstParts![Part Name]	' Also return Part Name field value.

Debug.Print rstParts![Part Type]	' Return Part Type field.

Debug.Print rstParts!Age	' Return Part Age field aliased as Age.


Fields Collection

A Fields collection contains all stored Field objects of an Index, QueryDef, Recordset, Relation, or TableDef object.

Remarks

The Fields collections of the Index, QueryDef, Relation, and TableDef objects contain the specifications for the fields those objects represent. The Fields collection of a Recordset object represents the Field objects in a row of data, or in a record. You use the Field objects in a Recordset object to read and to set values for the fields in the current record of the Recordset object.

You can refer to the Value property of a Field object that you create and append to a Fields collection by its Name property setting using the following syntax:

Fields("name")

Fields that have names with embedded spaces must be delimited with brackets ([ ]) or enclosed in double quotation marks (" "), using either of the following syntax forms:

Fields("long name")

You can refer to the Value property of a Field object that you create and append to a Fields collection by its position in the Fields collection using this syntax:

Fields(0)


Field Object, Fields Collection Summary

Field Object

A Field object contains these collections, methods, and properties.

Collection

Properties

Methods

AppendChunk

CreateProperty

FieldSize

GetChunk

Properties

AllowZeroLength

Attributes

CollatingOrder

DataUpdatable

DefaultValue

ForeignName

Name

OrdinalPosition

Required

Size

SourceField

SourceTable

Type

ValidateOnSet

ValidationRule

ValidationText

Value

Fields Collection

A Fields collection appears in each of the TableDef, QueryDef, Recordset, Relation, and Index objects, and contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Group Object

A Group object represents a group of user accounts that have common access permissions when a Workspace object operates as a secure workgroup.

Remarks

You create Group objects and then use their names to establish and enforce access permissions for your databases, tables, and queries using the Document objects that represent the database and database objects (tables and queries) you're working with.

You can append an existing Group object to the Groups collection in a User object to establish membership of a user account in that Group object. Alternatively, you can append a User object to the Users collection in a Group object to give a user account the global permissions of that group. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

Using the properties of a Group object, you can:

Check the Name property setting of an existing Group object to determine its name. You can't check the PID property setting of an existing Group object.

Set the Name and PID properties of a newly created, unappended Group object to establish the identity of that Group object.

The Microsoft Jet database engine predefines three Group objects named Admins, Users, and Guests.

You can refer to a Group object that you create and append to a Groups collection by its Name property setting using this syntax:

Groups("name")

To create a new Group object, use the CreateGroup method on a User or Workspace object.


Groups Collection

A Groups collection contains all stored Group objects of a Workspace or user account.

Remarks

You can append an existing Group object to the Groups collection in a User object or a Workspace object to establish membership of a user account in that Group object. Alternatively, you can append a User object to the Users collection in a Group object to give a user account the global permissions of that group. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

You can refer to a Group object that you create and append to a Groups collection by its Name property setting using this syntax:

Groups("name")

To create a new Group object, use the CreateGroup method.


Group Object, Groups Collection Summary

Group Object

The Group object contains these collections, methods, and properties.

Collections

Properties

Users (default)

Method

CreateUser

Properties

Name

PID

Groups Collection

A Groups collection appears in each User and Workspace object, and contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Index Object

Index objects specify the order of records accessed from database tables and whether or not duplicate records are accepted. Index objects also provide efficient access to data. For external databases, Index objects describe the indexes established for external tables.

Remarks

The Microsoft Jet database engine maintains all base table indexes automatically. Indexes are updated whenever you add, change, or delete records from the base table. Once the database is created, use the CompactDatabase method periodically to bring index statistics up-to-date.

The Jet database engine uses indexes when it joins tables and creates Recordset objects. Indexes determine the order of records returned by table-type Recordset objects, but they don't determine the order in which records are stored in the base table or the order of records returned from any other type of recordset.

When accessing a table-type Recordset object, you specify the order of records using the object's Index property. Set this property to the Name property setting of an existing Index object in the Indexes collection. This collection is contained by the TableDef object underlying the Recordset object that you're populating. For example, to order your table-type Recordset object by the ZIP_INDEX index, you could use the following code.

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

Set rstPublishers = dbsBiblio.OpenRecordset("Publishers", dbOpenTable)

rstPublishers.Index = "ZIP_INDEX"

Tip   You don't have to create indexes for a table, but for large, unindexed tables, accessing a specific record or processing joins can take a long time. Conversely, having too many indexes can slow down updates to the database as each of the table indexes is amended.

The Attributes property of each Field object in the index determines the order of records returned and consequently determines which access techniques to use for that index.

Each Field object in the Fields collection of an Index object is a component of the index. You define a new Index object by setting its properties before you append it to a collection, which makes the Index object available for subsequent use.

Note   You can modify the Name property setting of an existing Index object only if the Updatable property setting of the containing TableDef object is True.

Using an Index object and its properties, you can:

Use the Required property to determine whether the Field objects in the index require values that are not Null, then use the IgnoreNulls property to determine whether the Null values have index entries.

Use the Primary and Unique properties to determine the ordering and uniqueness of the Index object.

When you set a primary key for a table, the Jet database engine automatically defines it as the primary index. A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the primary index field must be unique, the Jet database engine automatically sets the Unique property of the primary Index object to True. If the primary index consists of more than one field, each field can contain duplicate values, but the combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and is always made up of the same fields as the primary key.

Important   Make sure your data complies with the attributes of your new index. If your index requires unique values, make sure that there are no duplicates in existing data records. If duplicates exist, the Jet database engine can't create the index, resulting in a trappable error when you attempt to use the Append method on the new index.

When you create a relationship that enforces referential integrity, the Jet database engine automatically creates an index with the Foreign property, set as the foreign key in the referencing table. After you've established a table relationship, the Jet database engine prevents additions or changes to the database that violate that relationship. If you set the Attributes property of the Relation object to allow cascade update and cascade delete operations, the Jet database engine updates or deletes records in related tables automatically.

To create a new Index object

1.	Use the CreateIndex method on the TableDef object.

2.	Use the CreateField method on the Index object to create a Field object for each field (column) to be included in the Index object.

3.	Set Index properties as needed.

4.	Append the Field object to the Fields collection.

5.	Append the Index object to the Indexes collection.

For example:

' Create new Index object.

Set idxAnother = tbdEmployees.CreateIndex("Another")

Set fldLastName = idxAnother.CreateField("LastName")

idxAnother.Primary = True

idxAnother.Required = True

idxAnother.Fields.Append fldLastName

' Save Index object definition by appending it to Indexes collection.

tbdEmployees.Indexes.Append idxAnother

Note   The Clustered property is ignored for databases that use the Jet database engine, which doesn't support clustered indexes.


Indexes Collection

An Indexes collection contains all the stored Index objects of a TableDef object.

Remarks

Once created, a new Index object should be added to the TableDef object's Indexes collection using the Append method.

When accessing a table-type Recordset object, you specify the order of records using the object's Index property. Set this property to the Name property setting of an existing Index object in the Indexes collection. This collection is contained by the TableDef object underlying the Recordset object that you're populating. For example, to order your table-type Recordset by the ZIP_INDEX index, you could use the following code.

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

Set rstPublishers = dbsBiblio.OpenRecordset("Publishers", dbOpenTable)

rstPublishers.Index = "ZIP_INDEX"

Note   You can use the Append or Delete method on an Indexes collection only if the Updatable property setting of the containing TableDef object is True.

If you attempt to create an Index object and your data doesn't comply with the attributes specified for the index, such as nonunique or Null values in an indexed field, a trappable error results when you attempt to use the Append method on the new index.


Index Object, Indexes Collection Summary

Index Object

The Index object contains these collections, methods, and properties.

Collections

Fields (default)

Properties

Methods

CreateField

CreateProperty

Properties

Clustered

DistinctCount

Foreign

IgnoreNulls

Name

Primary

Required

Unique

Indexes Collection

An Indexes collection appears in each TableDef object, and contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Parameter Object

A Parameter object represents a parameter associated with a QueryDef object created from a parameter query.

Remarks

Using the properties of a Parameter object, you can set a query parameter that can be changed before the query is run. You can:

 	Check the Name property setting to determine the name of a parameter.

 	Check or set the Value property (default) of a parameter. For example:

qdfNewHires.Parameters(0) = 5

 	Check the Type property setting to determine the data type of the Parameter object.

The Parameters collection provides information only about existing parameters. You can't append objects to, or delete objects from, the Parameters collection.

The only method supported by the Parameters collection is the Refresh method.


Parameters Collection

A Parameters collection contains all the Parameter objects of a QueryDef object.

Remarks

The Parameters collection provides information only about existing parameters. You can't append objects to or delete objects from the Parameters collection.

The only method supported by the Parameters collection is the Refresh method.


Parameter Object, Parameters Collection Summary

Parameter Object

A Parameter object contains no methods; it contains this collection and these properties.

Collection

Properties

Properties

Name

Type

Value

Parameters Collection

A Parameters collection appears in each QueryDef object and contains this method and this property.

Method

Refresh

Property

Count


Property Object

A Property object represents a built-in or user-defined characteristic of a data access object.

Remarks

Every data access object contains a Properties collection, which has certain built-in Property objects. These Property objects (which are often just called properties) uniquely characterize that instance of the object. You specify built-in properties when you create a new data access object. You can set the properties of some existing data access objects using an assignment statement.

The Property object also has four built-in properties:

The Name property, a String that uniquely identifies the property.

The Type property, an Integer that specifies the property data type.

The Value property, a Variant that contains the property setting.

The Inherited property, a Boolean flag that indicates whether the property is inherited from another object. For example, a Field object in a Fields collection of a Recordset object can inherit properties from the underlying TableDef or QueryDef object.

In addition to these built-in properties, you can create and add your own user-defined properties to these objects:

Database, Index, QueryDef, and TableDef objects

Field objects in Fields collections of QueryDef and TableDef objects

To add a user-defined property, use the CreateProperty method to create a Property object with a unique Name property setting. Set the Type and Value properties of the new Property object, and then append it to the Properties collection of the appropriate object. The object to which you are adding the user-defined property must already be saved to disk (that is, it must be appended to a collection).

You can delete user-defined properties from the Properties collection, but you can't delete built-in properties.

Note   A user-defined property (Property object) is associated only with the specific instance of the object whose Properties collection you append it to. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property (such as the Password property of a Workspace object), an error occurs.

You can refer to an existing built-in or user-defined property by its Name property setting using this syntax:

object.Properties("name")

For a built-in property, you can also use this syntax:

object.name

You can also reference properties by their ordinal position using this syntax, which refers to the first member of the Properties collection:

object.Properties(0)

A user-defined property differs from a built-in property of a data access object in the following ways:

You must refer to a user-defined property using the full Properties("name") syntax.

If you haven't previously set the property's value, you need to create it first using the CreateProperty method.


Properties Collection

A Properties collection contains all the Property objects for a specific instance of an object.

Remarks

Every data access object contains a Properties collection, which has certain built-in Property objects. These Property objects (which are often just called properties) uniquely characterize that instance of the object.

In addition to the built-in properties, some objects allow you to create and add your own user-defined properties. To add a user-defined property to an existing instance of an object, first define it's characteristics with the CreateProperty method, then add it to the collection with the Append method.

You can use the Delete method to remove user-defined properties from the Properties collection, but you can't remove built-in properties.

Note   A user-defined property (Property object) is associated only with the specific instance of the object whose Properties collection you append it to. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property, an error occurs.

You can refer to an existing built-in or user-defined property by its Name property setting using this syntax:

object.Properties("name")

For a built-in property, you can also use this syntax:

object.name

You can also reference properties by their ordinal position. For example, this syntax refers to the first member of the Properties collection:

object.Properties(0)

Note   A user-defined property differs from a built-in property of a data access object in that you must refer to a user-defined property using the full Properties("name") syntax.


Property Object, Properties Collection Summary

Property Object

The Property object contains no methods; it contains this collection and these properties.

Collection

Properties

Properties

Inherited

Name

Type

Value

Properties Collection

A Properties collection appears in each of the other data access objects, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


QueryDef Object

A QueryDef object is a stored definition of a query in a Microsoft Jet database.

Remarks

The QueryDef object corresponds to a stored query definition in a database. You can think of a saved query as a compiled SQL statement.

You can use the properties of a QueryDef object to define a query. For example, you can:

Check and modify the SQL property setting, set its parameters, and then run the query.

Set query parameters using the QueryDef object's Parameters collection.

Set or check the Type property to determine whether the query selects records from an existing table, makes a new table, inserts records from one table into another table, deletes records, or updates records.

Retrieve data from an ODBC data source by setting the ODBCTimeout and Connect properties and, if the query isn't a select query, setting the ReturnsRecords property to False.

Indicate the query is to be passed to an external ODBC server by setting the Connect property, making it an SQL pass through query.

Use the ReturnsRecords property to indicate that the query returns records. The ReturnsRecords property is only valid on SQL pass through queries.

Use the ODBCTimeout property to indicate how long to wait before the query returns records. The ODBCTimeout property applies to any query that accesses ODBC data.

Queries executed from QueryDef objects run faster than queries specified by the OpenRecordset method because the Microsoft Jet database engine doesn't need to compile the query before executing it.

The preferred way to use the native SQL dialect of an external database engine is by using QueryDef objects. For example, you can create a Transact SQL query (as used with Microsoft SQL Server) and store it in a QueryDef object. When you need to use a non-Jet database engine SQL query, you must provide a Connect property string that points to the external data source. Queries with valid Connect properties bypass the Jet database engine and pass the query directly to the external database server for processing.

To create a new QueryDef object, use the CreateQueryDef method.


QueryDefs Collection

A QueryDefs collection contains all QueryDef objects in a Database object.

Remarks

The QueryDef object corresponds to a stored query definition in a database. When you create a QueryDef object, you can add it to the QueryDefs collection using the Append method so it will be saved when you close the Database object.

To remove a QueryDef object from the collection, use the Delete method.


QueryDef Object, QueryDefs Collection Summary

QueryDef Object

The QueryDef object contains these collections, methods, and properties.

Collections

Fields

Parameters (default)

Properties

Methods

CreateProperty

Execute

OpenRecordset

Properties

Connect

DateCreated

LastUpdated

LogMessages

Name

ODBCTimeout

RecordsAffected

ReturnsRecords

SQL

Type

Updatabale

QueryDefs Collection

A QueryDefs collection appears in each Database object, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


Recordset Object

A Recordset object represents the records in a base table or the records that result from running a query.

Remarks

When you use data access objects, you interact with data almost entirely using Recordset objects. All Recordset objects are constructed using records (rows) and fields (columns). There are three types of Recordset objects:

Table-type Recordset [image] a representation in code of a base table that you can use to add, change, or delete records from a single database table.

Dynaset-type Recordset [image] the result of a query that can have updatable records. A dynaset-type Recordset object is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables. A dynaset-type Recordset object can contain fields from one or more tables in a database.

Snapshot-type Recordset [image] a static copy of a set of records that you can use to find data or generate reports. A snapshot-type Recordset object can contain fields from one or more tables in a database but can't be updated.

You can choose the type of Recordset object you want to create using the type argument of the OpenRecordset method. If you don't specify a type, the Microsoft Jet database engine attempts to create a table-type Recordset object. If this isn't possible, the Jet database engine attempts a dynaset-type and then a snapshot-type Recordset object.

When creating a Recordset object using a nonattached TableDef object, table-type Recordset objects are created. Only dynaset-type or snapshot-type Recordset objects can be created with attached tables or tables in external ODBC databases.

The Type property indicates the type of Recordset object created, and the Updatable property indicates whether you can change the object's records.

A new Recordset object is automatically added to the Recordsets collection when you open the object, and is automatically removed when you close it.

Information about the structure of a base table, such as the names and data types of each Field object and any Index objects, is stored in a TableDef object.

Note   If you use variables to represent a Recordset object and the Database object that contains the recordset, make sure the variables have the same scope, or lifetime. For example, if you declare a global variable that represents a Recordset object, make sure the variable that represents the database containing the recordset is also global, or is declared in a Sub or Function procedure using the Static keyword.

Your application can create as many Recordset object variables as needed. A Recordset object can refer to one or more tables or queries, or can be an SQL statement. You can also have a Recordset object that refers to some or all of the fields or records in other Recordset objects.

Dynaset- and snapshot-type Recordset objects are stored in local memory. If there isn't enough space in local memory to store the data, the Jet database engine saves the additional data to TEMP disk space. If this space is exhausted, a trappable error occurs.

The default collection of a Recordset object is the Fields collection, and the default property of a Field object is the Value property. You can simplify your code by using these defaults. For example, the following lines of code all set the value of the PubID field in the current record of a Recordset object.

rstPublishers!PubID = 99

rstPublishers("PubID") = 99

rstPublishers.Fields("PubID").Value = 99

When you create a Recordset object, the current record is positioned to the first record if there are any records. If there are no records, the RecordCount property setting is 0, and the BOF and EOF property settings are True.

You can use the MoveNext, MovePrevious, MoveFirst, and MoveLast methods to reposition the current record. For dynaset- and snapshot-type Recordset objects, you can also use the Find methods, such as FindFirst, to locate a specific record based on criteria. If the record isn't found, the NoMatch property is set to True. For table-type Recordset objects, you can scan records using the Seek function.

To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Recordset object. However, it may run faster to with an SQL query that performs operations that apply to an entire set of records.


Recordsets Collection

The Recordsets collection contains all open Recordset objects in a Database object.

Remarks

When you use data access objects, you interact with data almost entirely using Recordset objects.

A new Recordset object is automatically added to the Recordsets collection when you open the Recordset object, and is automatically removed when you close it.

Your application can create as many Recordset object variables as needed. A Recordset object can refer to one or more tables, queries alone, or queries referenced by other Recordset objects in any combination. You can also have a Recordset object that refers to some or all of the fields or records in other Recordset objects.


Recordset Object, Recordsets Collection Summary

Recordset Object

The Recordset object contains these collections, methods, and properties.

Collections

Fields (default)

Properties

Recordset Methods

The following table lists recordset methods and which objects support them.

Note   Snapshot-type Recordset objects created when you use the dbForwardOnly constant as the options argument with the OpenRecordset method don't support the methods and properties marked with an asterisk (*). In addition, the Move method can only be used with forward moves that don't use a bookmark offset.

Recordset object types

Method	Dynaset	Snapshot	Table

AddNew

CancelUpdate

Clone	*

Close

CopyQueryDef

Delete

Edit

FillCache

FindFirst	*

FindLast	*

FindNext	*

FindPrevious	*

GetRows

Move

MoveFirst	*

MoveLast	*

MoveNext

MovePrevious	*

OpenRecordset	*

Requery

Seek

Update

Recordset Properties

The following table indicates which properties apply to each type of Recordset object and whether the property setting is read/write, read-only, or always False.

Note   Snapshot-type Recordset objects that are created when you use the dbForwardOnly constant as the options argument with the OpenRecordset method don't support the methods and properties marked with an asterisk (*). In addition, the Move method can only be used with forward moves that don't use a bookmark offset.

Read-only

Read/write

Recordset object types

Property	Dynaset	Snapshot	Table

AbsolutePosition	*

BOF

Bookmark	*

Bookmarkable	*

CacheSize

CacheStart

DateCreated

EditMode

EOF

Filter

Index

LastModified

LastUpdated

LockEdits

Name

NoMatch

PercentPosition	*

RecordCount

Restartable	False

Sort

Transactions	False

Type

Updatable	False

ValidationRule

ValidationText

Recordsets Collection

A Recordsets collection appears in each Database object, and contains this method and this property.

Method

Refresh

Property

Count


Relation Object

A Relation object represents a relationship between fields in tables or queries.

Remarks

You can use the Relation object to create new relationships and examine existing relationships in your database. By setting the Attributes property, you can also use the Microsoft Jet database engine to enforce referential integrity.

Any changes you make to the database that violate the relationships established for the database result in a trappable error. If you request cascade update or cascade delete operations, the Jet database engine also modifies the primary or foreign key tables to enforce the relationships you establish.

An example of a typical relationship can be found between the NameAddress table and the ValidStateCodes table. The State field of the NameAddress table is the primary key, and the State field of the ValidStateCodes table is the foreign key. For a new record to be accepted in the NameAddress table, the Jet database engine searches the ValidStateCodes table for a match on the State field of the NameAddress table. If no match is found, the Jet database engine doesn't accept the new record, and a trappable error occurs.

Using a Relation object and its properties, you can:

Specify an enforced relationship between fields in base tables (but not a relationship that involves a query or an attached table).

Establish unenforced relationships between any type of table or query [image] native or attached.

Use the Name property to refer to the relationship between the fields in the referenced primary table and the referencing foreign table.

Use the Attributes property to determine whether the relationship between fields in the table is one-to-one or one-to-many and how to enforce referential integrity.

Use the Attributes property to determine whether the Jet database engine can perform cascade update and cascade delete operations on primary and foreign tables.

Use the Attributes property to determine whether the relationship between fields in the table is left join or right join.

The Name property settings of all Field objects in the Fields collection of a Relation object represent the names of the fields in the primary key of the referenced table. The ForeignName property settings of the Field objects represent the names of the fields in the foreign key of the referencing table.

When you enforce referential integrity, a unique index must already exist for the key field of the referenced table. The Jet database engine automatically creates an index with the Foreign property set to act as the foreign key in the referencing table.

To create a new Relation object, use the CreateRelation method.


Relations Collection

A Relations collection contains stored Relation objects of a Database object.

Remarks

You can use the Relation object to create new relationships and examine existing relationships in your database. You can add a Relation object to the Relations collection using the Append method so it will be saved when you close the Database object. To remove a Relation object from the collection, use the Delete method.


Relation Object, Relations Collection Summary

Relation Object

The Relation object contains these collections, methods, and properties.

Collections

Fields (default)

Properties

Methods

CreateField

Properties

Attributes

ForeignTable

Name

Table

Relations Collection

A Relations collection is contained in each Database object, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


Snapshot-Type Recordset Object

A snapshot-type Recordset object is a static set of records that you can use to examine data in an underlying table or tables. A snapshot-type Recordset object can contain fields from one or more tables in a database but can't be updated.

Remarks

When you create a snapshot-type Recordset object, data values for all fields (except Memo and OLE Object field data types in .mdb files) are brought into memory. Once loaded, changes made to base table data aren't reflected in the snapshot-type Recordset object data. To reload the snapshot-type Recordset object with current data, use the Requery method, or re-execute the OpenRecordset method.

The order of snapshot-type Recordset object data doesn't necessarily follow any specific sequence. To order your data, use an SQL statement with an ORDER BY clause to create the Recordset object. You can also use this technique to filter the records so that only certain records are added to the Recordset object. For example, the following code selects only titles whose name contains the string "VBSQL" and sorts the resulting records by ISBN:

Dim dbsBiblio As Database, rstTitles As Recordset
Dim strSelect As String

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

strSelect = "SELECT * FROM Titles WHERE Title like '*VBSQL*' " & _
"ORDER BY ISBN;"

Set rstTitles = dbsBiblio.OpenRecordset(strSelect,dbOpenSnapshot)

Using this technique instead of using the Filter or Sort properties or testing each record individually generally results in faster access to your data.

To create a snapshot-type Recordset object, use the OpenRecordset method on an open database, on another dynaset- or snapshot-type Recordset object, or on a QueryDef object.

Snapshot-type Recordset objects are generally faster to create and access than dynaset-type Recordset objects because their records are either in memory or stored in TEMP disk space, and the Microsoft Jet database engine doesn't need to lock pages or handle multiuser issues. However, snapshot-type Recordset objects use more resources than dynaset-type Recordset objects because the entire record is downloaded to local memory.


Table-Type Recordset Object

A table-type Recordset object is a representation in code of a base table you can use to add, change, or delete records from a table. Only the current record is loaded into memory. A predefined index is used to determine the order of the records in the Recordset object.

Remarks

To create a table-type Recordset object, use the OpenRecordset method on an open Database object.

A table-type Recordset object can be created with a base table of a Microsoft Jet database, but not with an ODBC or attached table. The table-type Recordset object can be used with ISAM databases (like FoxPro, dBASE, or Paradox) when opened directly.

Unlike dynaset- or snapshot-type Recordset objects, the table-type Recordset object can't refer to more than one base table, and it can't be accessed using an SQL statement that filters or sorts the data. Generally, when you access a table-type Recordset object, you specify one of the predefined indexes for the table, which orders the data returned to your application. If the table doesn't have an index, the order of the data returned can't be guaranteed. If necessary, your application can create an index that returns records in a specific order. To choose a specific order for your table-type Recordset object, set the Index property to a valid index.

To maintain data integrity, table-type Recordset objects are locked during the Edit and Update methods operations so that only one user can update a particular record at a time. When the Microsoft Jet database engine locks a record, it locks the entire 2K page containing the record.

Two kinds of locking are used with non-ODBC tables [image] pessimistic and optimistic. ODBC-accessed tables always use optimistic locking. The locking conditions in effect during editing are determined by the LockEdits property.


TableDef Object

A TableDef object represents the stored definition of a base table or an attached table.

Remarks

You manipulate a table definition using a TableDef object and its methods and properties. For example, you can:

Examine the field and index structure of any local, attached, or external table in a database.

Read or write the Connect and SourceTableName property settings for attached tables, and use the RefreshLink method to update connections to attached tables.

Read (or write, if the Updatable property is set to True (-1)) the ValidationRule and ValidationText property settings to find (or specify) validation conditions.

Use the OpenRecordset method to create a table-, dynaset-, or snapshot-type Recordset object, based on the table definition.

The default collection of a Database object is the TableDefs collection, and the default collection of a TableDef object is the Fields collection. You can simplify your code by using these defaults. For example, the following statements are identical in that they both print the number corresponding to the field data type of a Field object in a TableDef object:

Debug.Print dbsCurrent.TableDefs("Publishers").Fields("PubID").Type

Debug.Print dbsCurrent("Publishers")("PubID").Type

The Name property of a TableDef object isn't necessarily the same as the name of an object variable to which it's assigned.

For base tables, the RecordCount property contains the number of records in the specified database table. For attached tables, the RecordCount property setting is always -1.

You refer to a TableDef object that you create and append to a TableDefs collection by its Name property setting using this syntax:

TableDefs("name")

To create a new TableDef object, use the CreateTableDef method.

To make changes in the structure of a table, such as adding a field

1.	Make sure any Recordset objects based on the table are closed by all users.

2.	Create a Field object variable and set its properties using the CreateField method.

3.	Add the Field object to the Fields collection of the TableDef object using the Append method.

To create a table that is ready for new records in a database

1.	Create a TableDef object using the CreateTableDef method.

2.	Set its properties.

3.	Create a Field object variable and set its properties using the CreateField method for each field in the table.

4.	Add the fields to the Fields collection of the TableDef object using the Append method.

5.	Use the Append method to add the new TableDef object to the TableDefs collection of the Database object.

An attached table is linked to the database by the SourceTableName and Connect properties of the TableDef object.

To attach a table to a database

1.	Create a TableDef object using the CreateTableDef method.

2.	Set its Connect and SourceTableName properties (and optionally, its Attributes property).

3.	Add it to the TableDefs collection of a Database using the Append method.

You can delete a Field object from a TableDefs collection if it doesn't have any indexes assigned to it, but its underlying data is lost.


TableDefs Collection

A TableDefs collection contains all stored TableDef objects in a database.

Remarks

You manipulate a table definition using a TableDef object and its methods and properties.

The default collection of a Database object is the TableDefs collection.

You refer to a TableDef object that you create and append to a TableDefs collection by its Name property setting using this syntax:

TableDefs("name")


Tabledef Object, TableDefs Collection Summary

TableDef Object

A TableDef object contains these collections, methods, and properties.

Collections

Fields (default)

Indexes

Properties

Methods

CreateField

CreateIndex

CreateProperty

OpenRecordset

RefreshLink

Properties

Attributes

ConflictTable

Connect

DateCreated

LastUpdated

Name

RecordCount

SourceTableName

Updatable

ValidationRule

ValidationText

A TableDef object may also contain application-defined properties. For details on reading and setting these properties, refer to the application's online Help.

TableDefs Collection

A TableDefs collection is contained in each Database object, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


User Object

A User object represents a user account that has access permissions when a Workspace object operates as a secure workgroup.

Remarks

You use User objects to establish and enforce access permissions for the Document objects that represent databases, tables, and queries. Also, if you know the properties of a specific User object, you can create a new Workspace object that has the same access permissions as the User object.

You can append an existing User object to the Users collection of a Group object to give a user account the access permissions for that Group object. Alternatively, you can append the Group object to the Groups collection in a User object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

Using the properties of a User object, you can:

Check the Name property setting of an existing User object to determine its name. You can't check the PID and Password property settings of an existing User object.

Set the Name, PID, and Password properties of a newly created, unappended User object to establish the identity of that User object. If you don't set the Password property, it's set to a zero-length string ("").

The Microsoft Jet database engine predefines two User objects named Admin and Guest. The user Admin is a member of the Group object named Admins and Users; the user Guest is a member only of the Group object named Guests.

You can refer to any other User object that you create and append to a Users collection by its Name property setting using this syntax:

Workspaces(n)|Group.Users("name")

To create a new User object, use the CreateUser method.


Users Collection

A Users collection contains all stored User objects of a Workspace or Group object.

Remarks

You can append an existing User object to the Users collection of a Group object to give a user account the access permissions for that Group object. Alternatively, you can append the Group object to the Groups collection in a User object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

The Microsoft Jet database engine predefines two User objects named Admin and Guest. The user Admin is a member of the Group object named Admins and Users; the user Guest is a member only of the Group object named Guests.

You can refer to any other User object that you create and append to a Users collection by its Name property setting using this syntax:

Workspaces(n)|Group.Users("name")


User Object, Users Collection Summary

User Object

The User object contains these collections, methods, and properties.

Collections

Groups (default)

Properties

Methods

CreateGroup

NewPassword

Properties

Name

Password

PID

Users Collection

A Users collection is contained in each Group and Workspace object, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


Workspace Object

A Workspace object defines a session for a user. It contains open databases and provides mechanisms for simultaneous transactions and for a secure workgroup.

Remarks

Use the Workspace object to manage the current session or to start an additional session. In a session, you can open multiple databases, manage transactions, and establish security based on user names and passwords. For example, you can:

Create a Workspace object using the Name and UserName properties to establish a named, password-protected session. The session creates a scope in which you can open multiple databases and conduct one instance of nested transactions. Use the Close method to terminate a session.

Use the OpenDatabase method to open one or more existing databases on that Workspace.

Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction processing within a Workspace and use several Workspace objects to conduct multiple, simultaneous, and overlapping transactions.

Use the IsolateODBCTrans property to isolate multiple transactions that involve the same ODBC database.

When you start the Microsoft Jet database engine, you automatically create the default workspace, DBEngine.Workspaces(0). The settings of the Name and UserName properties of the default workspace are "#Default Workspace#" and "Admin," respectively. If security is enabled, the UserName property setting is the name of the user who logged on. If you use the OpenDatabase method without specifying a Workspace object, the default DBEngine.Workspaces(0) is used.

When you use transactions, all databases in the specified Workspace are affected [image] even if multiple Database objects are opened in the Workspace. For example, if you use a BeginTrans method, update several records in a database, and then delete records in another database, both the update and delete operations are rolled back when you use the Rollback method. You can create additional Workspace objects to manage transactions independently across Database objects.

Workspace objects are created using the CreateWorkspace method of the DBEngine object. After you create a new Workspace object, you must appended it to the Workspaces collection if you need to refer to it from the Workspaces collection. You can, however, use a newly created Workspace object without appending it to the Workspaces collection.

You can refer to any other Workspace object that you create and append to the collection by its Name property setting using this syntax:

Workspaces("name")

You can also refer to appended Workspace objects by their position in the Workspaces collection using this syntax (where n is the nth member of the Workspaces collection):

DBEngine.Workspaces(n)


Workspaces Collection

The Workspaces collection contains all active, unhidden Workspace objects of the DBEngine object. (Hidden Workspace objects are not appended to the collection and referenced by the variable to which they are assigned.)

Remarks

Use the Workspace object to manage the current session or to start an additional session.

When you start the Microsoft Jet database engine, you automatically create the default workspace, DBEngine.Workspaces(0).

New Workspace objects are created with the CreateWorkspace method of the DBEngine object. After you create a new Workspace object, you must appended it to the Workspaces collection if you need to refer to it from the Workspaces collection. You can, however, use a newly created Workspace object without appending it to the Workspaces collection.

You can refer to any other Workspace object that you create and append to the collection by its Name property setting using this syntax:

Workspaces("name")

You can also refer to appended Workspace objects by their position in the Workspaces collection using this syntax (where n is the nth member of the Workspaces collection):

DBEngine.Workspaces(n)


Workspace Object, Workspaces Collection Summary

Workspace Object

The Workspace object contains these collections, methods, and properties.

Collections

Databases (default)

Groups

Properties

Users

Methods

BeginTrans

Close

CommitTrans

CreateDatabase

CreateGroup

CreateUser

OpenDatabase

Rollback

Properties

IsolateODBCTrans

Name

UserName

Workspaces Collection

The Workspaces collection is contained in the DBEngine object, and contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


Accessing Data in a dBASE Database with DAO

You can either link dBASE tables (.dbf files) to your Microsoft Jet database or open them directly. The procedures for accessing the data in dBASE tables (versions III, IV, or 5.x) are similar to the procedures used to access data in other external data sources. Special considerations for using dBASE data are provided in the following sections.

Linking a dBASE Table

To link a dBASE table in your Jet database, use the OpenDatabase method to open the Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the dBASE table you want to link.

When specifying connection information for dBASE data, use the following specifications.

For	Use
Source database type	One of the following: •  dBASE III •  dBASE IV •  dBASE 5.0
Database name	The full path to the directory containing the dBASE files you intend to access.
Source table name	The name of the table (the .dbf filename without the extension or the complete filename with the extension but substituting a number sign (#) for the dot (.) that precedes the filename extension).
Example

The following example shows how to link an external dBASE IV table and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfLinkedTable As TableDef

 Open Jet database named Test.mdb.

Set dbsJet = OpenDatabase("C:\Access\Data\Test.mdb")

' Create TableDef object.

Set tdfLinkedTable = dbsJet.CreateTableDef("Linked dBASE Table")

' Set connection information.

tdfLinkedTable.Connect = "dBASE IV;DATABASE=\\dBASE\Data\AP"

tdfLinkedTable.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfLinkedTable

' Display confirmation message.

MsgBox "Finished linking " & tdfLinkedTable.SourceTableName & ".", 0

Opening a dBASE Table

To open a dBASE table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external dBASE III table directly and create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external dBASE database.

Set dbsJet = OpenDatabase _

("\\dBASE\Data\AP", False, False, "dBASE III;")

' Create Recordset object from Accounts table.

Set rstAccounts = dbsJet.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a dBASE file, Microsoft Jet translates each dBASE data type into the corresponding Microsoft Jet data type, as shown in the following table.

dBASE data type	Microsoft Jet data type
Character	String
Numeric, Float	Double
Logical	Boolean
Date	Date/Time
Memo	Memo
OLE	OLE
Deleted Records

In most cases, if you delete a record when working with external data, the record is actually removed from the source table. When working with dBASE tables, however, deleted records aren't actually removed until the table is packed using dBASE commands or utilities. The Microsoft Jet DBEngine.CompactDatabase method works only on Jet databases; it has no effect on dBASE databases.

You can tell Microsoft Jet not to include deleted records by setting the Deleted parameter of the Jet\3.0\Engines\Xbase folder in the Windows Registry to True. If you set the Deleted parameter to False, all records are included in any Recordset objects you create, including deleted records.

Indexes

When you link or open a dBASE table, you can tell Microsoft Jet to use one or more dBASE index (.ndx or .mdx) files to improve performance. Microsoft Jet keeps track of the indexes in a special information (.inf) file. When you use Visual Basic to link or open a dBASE table, you must create the .inf file using a text editor or use the one created by Microsoft Access. The name of the .inf file must correspond to the name of the external table. In order for Microsoft Jet to easily locate associated indexes, it's best to put the .inf file in the same directory as the associated table. However, if the table is on a read-only share, you can specify a different path using the INFPath entry in the Jet\3.0\Engines\Xbase folder in the Windows Registry.

Each entry in the .inf file contains an index number (using the identifiers NDXn for dBASE III or NDXn or MDXn for dBASE IV) and an index filename (for example, LastName.ndx). The entries are preceded by a source database type. As an example, the .inf file for a dBASE III table named Authors would be named Authors.inf, and could contain the following entries.

[dBASE III]

NDX1=AuthorID.ndx

NDX2=LastName.ndx

NDX3=Zip.ndx

To specify a unique index, add the index name for the unique index to the .inf file using the identifier UIDXn. Add the entry under the database type heading, as shown in the following example.

[dBASE III]

NDX1=AuthorID.ndx

NDX2=LastName.ndx

NDX3=Zip.ndx

UIDX1=AuthorID

When you use Microsoft Jet to update the data in your .dbf file, Microsoft Jet also updates the index files to reflect your changes. If you link or open a .dbf file and associate an index (.ndx or .mdx) file, Microsoft Jet needs to be able to find the index file to open the linked table. If you delete or move index files or the .inf file, Microsoft Jet can't use the index and doesn't keep the index up-to-date. If index files aren't current, keep in mind that your query results will be unpredictable.

Memo Fields

dBASE Memo fields are located in files separate from their associated tables. When linking or opening dBASE tables with associated Memo fields, the Memo files must be located in the same directory as the .dbf files.

Additional Information

For additional information, consult your dBASE documentation.


Accessing Data in a Lotus Spreadsheet with DAO

You can either link Lotus spreadsheets to your Microsoft Jet database or open them directly. The procedures for accessing the data in Lotus files (versions WKS, WK1, WK3, or WK4) are similar to the procedures used to access data in other external data sources. Special considerations for using Lotus data are provided in the following sections.

How to Reference Tables, Fields and Records

You can reference an entire Lotus spreadsheet, a named range of cells within a spreadsheet, or an arbitrary (unnamed) range of cells. The conventions for referring to sheets and arbitrary ranges differ depending on whether you are accessing single-sheet (WKS and WK1) or multi-sheet (WK3 and WK4) files.

To reference an entire WKS or WK1 spreadsheet, enter the filename. Use the number sign (#) to separate the filename and extension (for example, Sales#wk1). To reference an entire sheet in a WK3 or WK4 file, specify the sheet name followed by a colon (for example, SHEET1:).

To reference an arbitrary range of cells in a WKS or WK1 spreadsheet, specify the starting and ending cells of the range separated by two periods (for example, A1..E15). To reference an arbitrary range of cells in a WK3 or WK4 file, specify the sheet name followed by a colon and the starting and ending cells of the range separated by two periods (for example, SHEET1:A1..E15)

To reference a named range of cells in any Lotus spreadsheet, you must name the range before attempting to open or link it. You can name a range of cells by highlighting the range, choosing Range Name Create from the menu, and entering the name of the range (for example, ThirdQtrSales). The name you enter becomes the name of the data table linked or opened using the Lotus ISAM.

Linking a Lotus Spreadsheet

To link a Lotus spreadsheet in your Jet database, use the OpenDatabase method to open the Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Lotus file you want to link. You can specify either the named range within a spreadsheet or the entire spreadsheet.

When specifying connection information for Lotus data, use the following specifications.

For	Use
Source database type	Lotus WKS*, Lotus WK1**, Lotus WK3**, or Lotus WK4**.
Database name	The full path to the Lotus worksheet.
Source table name	The name of the worksheet or a range specified in the worksheet.
*	Lotus WKS and WK4 worksheets are opened as read-only data sources; you cannot add, edit, or delete rows.
**	Lotus WK1 and WK3 worksheets are opened as write once, read many data sources; you can add new rows, but you cannot edit or delete existing rows.
Example

The following example shows how to link an external Lotus spreadsheet and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfThirdQtr As TableDef

' Open Jet database named Northwind.mdb.

Set dbsJet = OpenDatabase("C:\DB\Data\Northwind.mdb")

' Create TableDef object.

Set tdfThirdQtr = dbsJet.CreateTableDef("Linked Lotus Table")

' Link Lotus range Third Quarter in spreadsheet

' C:\Lotus\Examples\Sales.wk3.

tdfThirdQtr.Connect = "LOTUS WK3; _
Database=C:\Lotus\Examples\Sales.wk3"

tdfThirdQtr.SourceTableName = "THIRDQTR"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfThirdQtr

' Display confirmation message.

MsgBox "Finished linking " & tdfThirdQtr.SourceTableName & ".", 0

Opening a Lotus Spreadsheet

To open a Lotus spreadsheet directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external Lotus spreadsheet and then create a Recordset object from the named range THIRDQTR.

Dim dbsJet As Database

Dim rstThirdQtr As Recordset

' Open external Lotus spreadsheet table.

Set dbsJet = OpenDatabase _

("C:\Lotus\Examples\Sales.wk3", False, False, "LOTUS WK3;")

' Create Recordset object from Sales worksheet range "THIRDQTR".

Set rstThirdQtr = dbsJet.OpenRecordset("THIRDQTR")

Additional Information

For additional information, consult your Lotus documentation.


Accessing Data in a Microsoft Excel Worksheet or Workbook with DAO

You can either link Microsoft Excel worksheets and workbooks to your Microsoft Jet database or open them directly. The procedures for accessing the data in Microsoft Excel files (versions 3.0, 4.0, 5.0, or 7.0) are similar to the procedures used to access data in other external data sources. Special considerations for using Microsoft Excel data are provided in the following sections.

How to Reference Tables, Fields and Records

You can reference either a Microsoft Excel worksheet, a worksheet within a workbook, a named range of cells within a worksheet, or an arbitrary (unnamed) range of cells in a worksheet (for example, A1:E15). The conventions for referring to worksheets and arbitrary ranges differ depending on whether you are accessing single-sheet (Microsoft Excel 3.0 and Microsoft Excel 4.0) or workbook (Microsoft Excel 5.0 and Microsoft Excel 7.0) files.

To reference an entire Microsoft Excel 3.0 or Microsoft Excel 4.0 worksheet, enter the filename. Use the number sign (#) to separate the filename and extension (for example, Sales#xls). To reference an entire sheet in a Microsoft Excel 5.0 and Microsoft Excel 7.0 workbook, specify the sheet name followed by a dollar sign (for example, SHEET1$).

To reference an arbitrary range of cells in a Microsoft Excel 3.0 or Microsoft Excel 4.0 worksheet, specify the starting and ending cells of the range separated by a colon (for example, A1:E15). To reference an arbitrary range of cells in a worksheet in a Microsoft Excel 5.0 and Microsoft Excel 7.0 workbook, specify the sheet name followed by a dollar sign and the starting and ending cells of the range separated by a colon (for example, SHEET1$A1:E15)

To reference a named range of cells in any Microsoft Excel worksheet, you must name the range before attempting to open or link it. You can name a range of cells by highlighting the range, clicking Insert Name Define on the Insert menu, and entering the name of the range (for example, ThirdQtrSales). The name you enter becomes the name of the data table linked or opened using the Microsoft Excel ISAM.

Linking a Microsoft Excel Worksheet

To link a Microsoft Excel worksheet or workbook in your Jet database, use the OpenDatabase method to open the Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Microsoft Excel file you want to link. You can specify either the named range within a worksheet, the entire worksheet, or the entire workbook.

When specifying connection information for Microsoft Excel data, use the following specifications.

For	Use
Source database type	Microsoft Excel 3.0, Microsoft Excel 4.0, Microsoft Excel 5.0, or Microsoft Excel 7.0.
Database name	The full path to the Microsoft Excel worksheet or workbook.
Source table name	The name of the worksheet or a range specified in the worksheet. The Jet database engine does not recognize the exclamation point (!); it uses the dollar sign ($) instead. For example, the worksheet name SHEET!NAME is shown as table SHEET$NAME. If you use quotation marks in the sheet name in Microsoft Excel, you must also use them when you specify it as part of the table name. For example, `MY SHEET’$NAME.
Example

The following example shows how to link an external Microsoft Excel worksheet and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfThirdQtr As TableDef

' Open Jet database named Northwind.mdb.

Set dbsJet = OpenDatabase("C:\DB\Data\Northwind.mdb")

' Create TableDef object.

Set tdfThirdQtr = dbsJet.CreateTableDef("Linked Microsoft Excel" &_ 	"Table")

' Link Microsoft Excel table Third Quarter in worksheet
' C:\Excel\Examples\Sales.xls.

tdfThirdQtr.Connect = "EXCEL 5.0; Database=C:\Excel\Examples\Sales.xls"

tdfThirdQtr.SourceTableName = "THIRDQTR"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfThirdQtr

' Display confirmation message.

MsgBox "Finished linking " & tdfThirdQtr.SourceTableName & ".", 0

Opening a Microsoft Excel Worksheet

To open a Microsoft Excel worksheet directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external Microsoft Excel worksheet and then create a Recordset object from the named range THIRDQTR.

Dim dbsJet As Database

Dim rstThirdQtr As Recordset

' Open external Microsoft Excel worksheet table.

Set dbsJet = OpenDatabase _

("C:\Excel\Examples\Sales.xls", False, False, "EXCEL 5.0;")

' Create Recordset from Sales worksheet.

Set rstThirdQtr = dbsJet.OpenRecordset("THIRDQTR")

Special Caveats for Using Microsoft Excel Worksheets

You cannot delete rows from Microsoft Excel worksheets. You can clear data from individual cells in the worksheet, but you cannot modify cells that contain formulas. Also, you cannot create indexes. Data that has been encrypted in Microsoft Excel cannot be read by the Microsoft Excel driver. If the database engine encounters encrypted data, you will not be able to access that data.

Additional Information

For additional information, consult your Microsoft Excel documentation.


Accessing Data in a Microsoft FoxPro Database with DAO

You can either link Microsoft FoxPro tables to your Microsoft Jet database or open them directly. The procedures for accessing the data in FoxPro files (versions 2.0, 2.5, 2.6, 3.0, or DBC) are similar to the procedures used to access data in other external data sources. Special considerations for using FoxPro data are provided in the following sections.

Linking a Microsoft FoxPro Table

To link a Microsoft FoxPro table in your Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the FoxPro table you want to link.

When specifying connection information for FoxPro data, use the following specifications.

For	Use
Source database type	One of the following: •  FoxPro 2.0 •  FoxPro 2.5 •  FoxPro 2.6 •  FoxPro 3.0 •  FoxPro DBC
Database name	The full path to the directory containing the FoxPro files you intend to access (for Microsoft FoxPro DBC, the path must include the name of the DBC file).
Source table name	The name of the table (the .dbf filename without the extension or the complete filename with the extension but substituting a number sign (#) for the dot (.) that precedes the filename extension; for Microsoft FoxPro DBC, use the table name in the DBC).
Example

The following example shows how to link an external FoxPro version 2.5 table and then display a message box as confirmation. Note that this example uses a number sign (#) in the SourceTableName property to specify a nonstandard extension (.xyz).

Dim dbsJet As Database

Dim tdfFoxTable As TableDef

' Open Jet database named Test.mdb.

Set dbsJet = OpenDatabase("C:\Access\Data\Test.mdb")

' Create TableDef object.

Set tdfFoxTable = dbsJet.CreateTableDef("Linked FoxPro Table")

' Set connection information.

tdfFoxTable.Connect = "FoxPro 2.6;DATABASE=\\FoxPro\Data\AP"

tdfFoxTable.SourceTableName = "Accounts#xyz"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfFoxTable

' Display confirmation message.

MsgBox "Finished linking " & tdfFoxTable.SourceTableName & ".", 0

Opening a Microsoft FoxPro Table

To open a Microsoft FoxPro table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external FoxPro version 2.0 table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external FoxPro database.

Set dbsJet = OpenDatabase _

("\\FoxPro\Data\AP", False, False, "FoxPro 2.0;")

' Create Recordset object from Accounts table.

Set rstAccounts = dbsJet.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a FoxPro file, Microsoft Jet translates each FoxPro data type into the corresponding Microsoft Jet data type, as shown in the following table.

FoxPro data type	Microsoft Jet data type
Character	String
Numeric, Float	Double
Logical	Boolean
Date	Date/Time
Memo	Memo
General	OLE Object
Double*	Double
Currency*	Currency
Long*	Long
DateTime*	Date/Time
*	Microsoft FoxPro 3.0 and Microsoft FoxPro DBC only
Deleted Records

In most cases, if you delete a record when working with external data, the record is actually removed from the source table. When working with FoxPro tables, however, deleted records aren't actually removed until the table is packed using FoxPro commands or utilities. The Microsoft Jet DBEngine.CompactDatabase method works only on Jet databases; it has no effect on Microsoft FoxPro databases.

You can tell the Jet database engine not to include deleted records by setting the Deleted parameter of the Jet\3.0\Engines\Xbase folder in the Windows Registry to True. If you set the Deleted parameter to False, all records are included in any Recordset objects you create, even deleted records.

Indexes

When you link or open a FoxPro table, you can tell Microsoft Jet to use one or more FoxPro index (.idx or .cdx) files to improve performance. Microsoft Jet keeps track of the indexes in a special information (.inf) file. When you use Visual Basic to link or open a FoxPro table, you must create the .inf file using a text editor. The name of the .inf file must correspond to the name of the external table. In order for Microsoft Jet to easily locate associated indexes, it's best to put the .inf file in the same directory as the associated table. However, if the table is on a read-only share, you can specify a different path using the INFPath entry in the Jet\3.0\Engines\Xbase folder in the Windows Registry. You can also use the index created by Microsoft Access if you use Microsoft Access to link or open a FoxPro table.

Each entry in the .inf file contains an index number (using the identifiers CDXn or IDXn) and an index filename (for example, LastName.cdx). The entries are preceded by a source database type. As an example, the .inf file for a FoxPro 2.0 table named Authors would be named Authors.inf, and could contain the following entries.

[FoxPro 2.0]

CDX1=AuthorID.idx

CDX2=LastName.idx

CDX3=Zip.idx

To specify a unique index, add the tag or filename for the unique index to the .inf file using the identifier UIDXn. If the table will be opened only from version 2.0 of the Jet database engine, add the entry under the database type heading, as shown in the following example.

[FoxPro 2.0]

CDX1=AuthorID.idx

CDX2=LastName.idx

CDX3=Zip.idx

UIDX1=AuthorID

When you use Microsoft Jet to update the data in your .dbf file, Microsoft Jet also updates the index files to reflect your changes. If you link or open a .dbf file and associate an index (.idx or .cdx) file, Microsoft Jet needs to be able to find the index file to open the linked table. If you delete or move index files or the .inf file, Microsoft Jet can't use the index and doesn't keep the index up-to-date. If index files aren't current, keep in mind that your query results will be unpredictable.

Memo Fields

FoxPro Memo fields are located in files separate from their associated tables. When linking or opening FoxPro tables with associated Memo fields, the Memo files must be located in the same directory as the .dbf files.

Additional Information

For additional information, consult your Microsoft FoxPro documentation.


Accessing Data in a Microsoft Jet 2.x Database with DAO

You can either link external Microsoft Jet tables to your local Microsoft Jet database or open them directly. The procedures for accessing the data in external Microsoft Jet tables are similar to the procedures used to access data in other external data sources.

Linking an External Microsoft Jet Table

To link an external Microsoft Jet table in your local Jet database, use the OpenDatabase method to open the local Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the external Microsoft Jet table you want to link.

When specifying connection information for external Microsoft Jet tables, use the following specifications.

For	Use
Source database type	Not applicable.
Database name	The full path to the .mdb file.
Source table name	The name of the table.
Example

The following example shows how to link an external Microsoft Jet table and then display a message box as confirmation. Notice that the connection string begins with just a semicolon (;) rather than a source database type. A source database type isn't applicable when connecting to external databases that use the Microsoft Jet database engine.

Dim dbsJet As Database

Dim tdfJetTable As TableDef

' Open Jet database named Test.mdb.

Set dbsJet = OpenDatabase("C:\Access\Data\Test.mdb")

' Create TableDef object.

Set tdfJetTable = dbsJet.CreateTableDef("Linked Jet Table")

' Set connection information.

tdfJetTable.Connect = ";DATABASE=\\Access\Data\AP.mdb"

tdfJetTable.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfJetTable

' Display confirmation message.

MsgBox "Finished linking " & tdfJetTable.SourceTableName & ".", 0

Opening an External Microsoft Jet Table

To open an External Microsoft Jet table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external Microsoft Jet table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external Jet database named AP.

Set dbsJet = OpenDatabase _

("\\Access\Data\AP.mdb", False, False, "")

' Open a Recordset on Accounts table.

Set rstAccounts = dbsJet.OpenRecordset("Accounts")


Accessing Data in a Paradox Database with DAO

You can either link Paradox tables to your local Microsoft Jet database or open them directly. The procedures for accessing the data in Paradox files (versions 3.x, 4.x, and 5.x) are similar to the procedures used to access data in other external data sources. Special considerations for using Paradox data are provided in the following sections.

Linking a Paradox Table

To link a Paradox table in your Microsoft Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Paradox table you want to link.

When specifying connection information for Paradox tables, use the following specifications.

For	Use
Source database type	One of the following: •  Paradox 3.X •  Paradox 4.X •  Paradox 5.X
Database name	The full path to the directory containing the Paradox files you intend to access.
Source table name	The name of the table (the .db filename without the extension).
Example

The following example shows how to link an external Paradox version 3.x table and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfParadox As TableDef

' Open Jet database named Test.mdb.

Set dbsJet = OpenDatabase("C:\Access\Data\Test.mdb")

' Create TableDef object.

Set tdfParadox = dbsJet.CreateTableDef("Linked Paradox _

Table")

' Set connection information.

tdfParadox.Connect = "Paradox 3.X;DATABASE=\\PDOX\Data\AP"

tdfParadox.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfParadox

' Display confirmation message.

MsgBox "Finished linking " & tdfParadox.SourceTableName & ".", 0

Opening a Paradox Table

To open a Paradox table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external Paradox version 4.x table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external Paradox database named AP.

Set dbsJet = OpenDatabase _

("\\PDOX\Data\AP", False, False, "Paradox 4.X;")

' Create Recordset from Accounts table.

Set rstAccounts = dbsJet.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a Paradox table, Microsoft Jet translates each Paradox data type into the corresponding Microsoft Jet data type, as shown in the following table.

Paradox data type	Microsoft Jet data type
Alphanumeric	Text
Number	Double
Short number	Integer
Currency	Currency
Date	Date/Time
Memo	Memo
OLE	OLE Object (note that the Jet database engine recognizes the object but will not let you open it)
Logical (Paradox 5.X)	Boolean
Integer (Paradox 5.X)	Long
Timestamp (Paradox 5.X)	Date/Time
Binary (Paradox 5.X)	Byte
BCD (Paradox 5.X)	Double
Time (Paradox 5.X)	Date/Time
Autoinc (Paradox 5.X)	Counter
Note   Paradox Graphic, Binary, and Formatted memo types aren't supported and will not appear when you display external Paradox tables.

Indexes and Keys

Paradox stores important information about a table's primary key in an index (.px) file. If you link or open a Paradox table that has a primary key, Microsoft Jet needs to be able to find the .px file to open the linked table. After you've linked a Paradox table, if you delete or move the associated .px file, you won't be able to open the external table.

If you link or open a Paradox table that doesn't have a primary key, you can't update data in the table using Microsoft Jet, and you can't open the table in shared mode. If you want to be able to update the table or open the table in shared mode, define a primary key for the table using Paradox commands.

Network Paths

When you link or open a Paradox table that resides on a server and is shared by multiple users, you must set the ParadoxNetPath option in the Jet\3.0\Engines\Paradox folder of the Windows Registry to the path for either the Paradox.net file (for Paradox 3.x) or the Pdoxusrs.net file (for Paradox 4.x). For example, if the Paradox.net file is on drive Q in the WRKGRP directory, set ParadoxNetPath as follows.

ParadoxNetPath=Q:\WRKGRP

Important   The ParadoxNetPath, including the drive letter, must be consistent for all users sharing a particular database (directory). For example, if the Paradox.net file is in the WRKGRP directory on drive Q for one user of the database, it must be in the WRKGRP directory on drive Q for all other users of the database.

You must also set the ParadoxUserName and ParadoxNetStyle options. For information on these options, as well as other Paradox driver settings, see Initializing the Paradox Database Driver.

Additional Information

For additional information, consult your Paradox documentation.


Accessing Data in a Text Document with DAO

You can either link or directly open text files, which can be stored in either fixed-width or delimited format. The procedures for retrieving the data in text files are similar to those used to access data in other external data sources. However, unlike other database types, text databases have no standard schema or structure that you can determine by inspection. For this reason, you need to create a Schema.ini that describes your text file database so that the ISAM driver can manipulate the data.

Linking a Text File

To link a text file in your Microsoft Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the text file you want to link.

When specifying connection information for text files, use the following specifications.

For	Use
Source database type	Text.
Database name	The full path to the directory containing the text file you intend to access.
Source table name	The name of the text file including the extension (if no extension is specified, the default .txt extension is used).
Example

The following example shows how to link an external text file and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfTextData As TableDef

' Open Jet database named Northwind.mdb.

Set dbsJet = OpenDatabase("C:\DB\Data\Northwind.mdb")

' Create TableDef object.

Set tdfTextData = dbsJet.CreateTableDef("Linked Text _

Data")

' Set connection information.

tdfTextData.Connect = "TEXT; Database = C:\Winword\Staff"

tdfTextData.SourceTableName = "AWARDS"

' Append TableDef object to create link.

dbsJet.TableDefs.Append tdfTextData

' Display a confirmation message.

MsgBox "Finished linking " & tdfTextData.SourceTableName & ".", 0

Opening a Text File

To open a text file directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external text file and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAwards As Recordset

' Open external text data file.

Set dbsJet = OpenDatabase _

("C:\Winword\Data", False, False, "TEXT;")

' Create Recordset from Awards table.

Set rstAwards = dbsJet.OpenRecordset("AWARDS")

Special Caveats for Using Text Files

A text file can be opened only for a single user, because the Jet database engine doesn't support multiple users of text files.

You can read both delimited and fixed-width text files. The Jet database engine recognizes commas, tabs, and custom delimiters when dealing with delimited text data, but you must use the same delimiter consistently. Null data is denoted by two consecutive delimiters. For example, if your delimiter is a comma (,), two commas (,,) denote a Null value. If you are using fixed-width data, you can specify the format of the data in a Schema.ini file (see the following). Null fixed-width data is represented as spaces.

Tables are limited to a maximum of 255 fields. Field names are limited to 64 characters, and field widths are limited to 32,766 characters. Records are limited to 65,000 bytes.

Customizing the Schema.ini File

To read, import, or export text data, you need to create a Schema.ini file in addition to including the Text ISAM information in the .ini file. Schema.ini contains the specifics of a text data source: how the text file is formatted, how it is read at import time, and the default export format for files. The following examples show the layout for a fixed-width file, Filename.txt.

[Filename.txt]

ColNameHeader=False

Format=FixedLength

MaxScanRows=25

CharacterSet=OEM

Col1=columnname Char Width 24

Col2=columnname2 Date Width 9

Col3=columnname7 Float Width 10

Col4=columnname8 Integer Width 10

Col5=columnname9 LongChar Width 10

Similarly, the format for a delimited file is specified as:

[Delimit.txt]

ColNameHeader=True

Format=Delimited(!)

MaxScanRows=0

CharacterSet=OEM

Col1=username char width 50

Col2=dateofbirth Date width 9

If you are exporting data into a delimited text file, specify the format for that file as well.

[Export: My Special Export]

ColNameHeader=True

Format=TabDelimited

MaxScanRows=25

CharacterSet=OEM

DateTimeFormat=mm.dd.yy.hh.mm.ss

CurrencySymbol=Dm

CurrencyPosFormat=0

CurrencyDigits=2

CurrencyNegFormat=0

CurrencyThousandSymbol=,

CurrencyDecimalSymbol=.

DecimalSymbol=,

NumberDigits=2

NumberLeadingZeros=0

The My Special Export example refers to a specific export option; you can specify any variation of export options at connect time. This last example also corresponds to a data source name (DSN) that can be optionally passed at connect time. All three format sections can be included in the same .ini file.

The Jet database engine uses the Schema.ini entries as follows.

Entry	Description
ColNameHeader	Can be set to either True (indicating that the first record of data specifies the column names) or False.
Format	Can be set to one of the following values: TabDelimited, CSVDelimited, Delimited(<single character delimiter), or FixedLength. The delimiter specified for the Delimited file format can be any single character except a double quotation mark (").
MaxScanRows	Indicates the number of rows to be scanned when guessing the column data types. If this is set to 0, the entire file is searched.
CharacterSet	Can be set to OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.
DateTimeFormat	Can be set to a format string indicating dates and times. This entry should be specified if all date/time fields in the import/export are handled with the same format. All of the Jet database engine formats except AM and PM are supported. In the absence of a format string, the Windows Control Panel short date picture and time options are used.
CurrencySymbol	Indicates the currency symbol to be used for currency values in the text file. Examples include the dollar sign ($) and Dm. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyPosFormat	Can be set to any of the following values: 0 Currency symbol prefix with no separation ($1) 1 Currency symbol suffix with no separation (1$) 2 Currency symbol prefix with one character separation ($ 1) 3 Currency symbol suffix with one character separation (1 $) If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyDigits	Specifies the number of digits used for the fractional part of a currency amount. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyNegFormat	Can be one of the following values: 0 ($1) 1 –$1 2 $–1 3 $1– 4 (1$) 5 –1$ 6 1–$ 7 1$– 8 –1 $ 9 –$ 1 10 1 $– 11 $ 1– 12 $ –1 13 1– $ 14 ($ 1)  15 (1 $) The dollar sign is shown for purposes of this example, but it should be replaced with the appropriate CurrencySymbol value in the actual program. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyThousandSymbol	Indicates the single-character symbol to be used for separating currency values in the text file by thousands. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyDecimalSymbol	Can be set to any single character that is used to separate the whole from the fractional part of a currency amount. If this entry is absent, the default value in the Windows Control Panel is used.
DecimalSymbol	Can be set to any single character that is used to separate the integer from the fractional part of a number. If this entry is absent, the default value in the Windows Control Panel is used.
NumberDigits	Indicates the number of decimal digits in the fractional portion of a number. If this entry is absent, the default value in the Windows Control Panel is used.
NumberLeadingZeros	Specifies whether a decimal value less than 1 and greater than –1 should contain leading zeros; this value can either be False (no leading zeros) or True.
Col1, Col2, ...	Lists the columns in the text file to be read. The format of this entry should be: Coln=columnName type [Width #] columnName: Column names with embedded spaces should be enclosed in quotation marks. type: Can be Bit, Byte, Short, Long, Currency, Single, Double, DateTime, Text, or Memo. In addition, the following ODBC Text Driver types are supported: Char (same as Text) Float (same as Double) Integer (same as Short) LongChar (same as Memo) Date date format


Initializing the dBASE Database Driver

When you install the dBASE database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the dBASE database driver.

dBASE Initialization Settings

The Jet\3.0\Engines\Xbase folder includes initialization settings for the MSXB3032.dll driver, used for access to external dBASE data sources. Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXB3032.dll

NetworkAccess=On

PageTimeout=600

INFPath=C:\DBASE\SYSTEM

CollatingSequence=ASCII

DataCodePage=OEM

Deleted=On

Century=Off

Date=MDY

Mark=47

Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows.

Entry	Description
win32	The location of MSXB3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
NetworkAccess	A binary indicator for file locking preference. If NetworkAccess is set to 00, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument. The default value is 01. Values are of type REG_BINARY.
PageTimeout	The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type REG_DWORD.
INFPath	The full path to the .inf file directory. The Microsoft Jet database engine first looks for an .inf file in the directory containing the table. If the .inf file isn't in the database directory, it looks in the INFPath. If there is no INFPath, it uses whatever index files (.cdx or .mdx) it finds in the database directory. Values are of type REG_SZ. This entry is not written by the installation procedure.
CollatingSequence	The collating sequence for all dBASE tables created or opened using Microsoft Jet. Possible values are ASCII and International. The default is ASCII. Values are of type REG_SZ.
DataCodePage	An indicator of how text pages are stored. Possible settings are: • OEM OemToAnsi and AnsiToOem conversions done. • ANSI OemToAnsi and AnsiToOem conversions not done. The default is OEM. Values are of type REG_SZ.
Deleted	A binary indicator that determines how records marked for deletion are handled by the Microsoft Jet database engine. A value of 01 corresponds to the dBASE command SET DELETED ON and indicates never to retrieve or position on a deleted record. A value of 00 corresponds to the dBASE command SET DELETED OFF and indicates to treat a deleted record like any other record. The default is 00. Values are of type REG_BINARY.
Century	A binary indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions. A value of 01 corresponds to the dBASE command SET CENTURY ON and a value of 00 corresponds to the dBASE command SET CENTURY OFF. The default is 00. Values are of type REG_BINARY.
Date	The date formatting style to use in cases where date-to-string functions are used in index expressions. The possible settings for this entry, which corresponds to the dBASE SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD. The default is MDY. Values are of type REG_SZ.
Mark	The decimal value of the ASCII character used to separate date parts. The default depends on the Date setting as follows: • "/" (American, MDY) • "." (ANSI) • "/" (British, French, DMY) • "." (German) • "-" (Italian) • "/" (Japan, YMD) • "-" (USA) A value of 0 specifies that the system should use the separator usually associated with the selected date format. The default is 0. Values are of type REG_DWORD.
Exact	A binary indicator for string comparisons. A value of 01 corresponds to the dBASE command SET EXACT ON. A value of 00 corresponds to the dBASE command SET EXACT OFF. The default is 00. Values are of type REG_BINARY.
dBASE ISAM Formats

The Jet\3.0\ISAM Formats\dBASE III folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	dBASE III (*.dbf)
ImportFilter	REG_SZ	dBASE III (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	dBASE Index (*.ndx)
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a dBASE III file. This process will overwrite the data if exported to an existing file.
'

The Jet\3.0\ISAM Formats\dBASE IV folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	dBASE IV (*.dbf)
ImportFilter	REG_SZ	dBASE IV (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	dBASE Index (*.ndx; *.mdx)
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a dBASE IV file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\dBASE 5.x folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	dBASE 5.0 (*.dbf)
ImportFilter	REG_SZ	dBASE 5.0 (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	dBASE Index (*.ndx; *.mdx)
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a dBASE 5 file. This process will overwrite the data if exported to an existing file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Lotus Driver

When you install the Lotus database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Lotus database driver.

Lotus Initialization Settings

The Jet\3.0\Engines\Lotus folder includes initialization settings for the MSLT3032.dll driver, used for external access to Lotus spreadsheets. Typical settings for the entries under this heading are shown in the following example.

win32=<pathname>\MSLT3032.dll

TypeGuessRows=8

ImportMixedTypes=Text

AppendBlankRows=4

FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Lotus folder entries as follows.

Entry	Description
win32	The location of MSLT3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
TypeGuessRows	The number of rows to be checked for the data type. The data type is determined based on the most frequently found data type in the selection. If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Long Text. If data is encountered that does not match the data type guessed for the column, it is returned as a Null value. On import, if a column has mixed data types, the entire column will be converted according to the ImportMixedTypes setting. The default number of rows to be checked is 8. Values are of type REG_DWORD.
ImportMixedTypes	Can be set to MajorityType or Text. If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import. If set to Text, columns of mixed data types will be cast to Text on import. The default is Text. Values are of type REG_SZ.
AppendBlankRows	The number of blank rows to be appended to the end of a WK1 worksheet before new data is added. For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data. Integer values for this setting can range from 0 to 16; the default is 0 (no additional rows appended). Values are of type REG_DWORD.
FirstRowHasNames	A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row; column names appear as F1, F2, F3, and so on. The default is 01. Values are of type REG_BINARY.
Lotus ISAM Formats

The Jet\3.0\ISAM Formats\Lotus WK1 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Lotus
ExportFilter	REG_SZ	Lotus 1-2-3 WK1 (*.wk1)
ImportFilter	REG_SZ	Lotus 1-2-3 WK1 (*.wk*)
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a Lotus 1-2-3 Version 2 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Lotus WK3 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Lotus
ExportFilter	REG_SZ	Lotus 1-2-3 WK3 (*.wk3)
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
ResultTextExport	REG_SZ	Export data from the current database into a Lotus 1-2-3 Version 3 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Lotus WK4 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Lotus
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Excel Driver

When you install the Microsoft Excel database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft Excel database driver.

Microsoft Excel Initialization Settings

The Jet\3.0\Engines\Excel folder includes initialization settings for the MSXL3032.dll driver, used for external access to Microsoft Excel worksheets. Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXL3032.dll

TypeGuessRows=8

ImportMixedTypes=Text

AppendBlankRows=4

FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Excel folder entries as follows.

Entry	Description
win32	The location of MSXL3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
TypeGuessRows	The number of rows to be checked for the data type. The data type is determined given the maximum number of kinds of data found. If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Boolean. If data is encountered that does not match the data type guessed for the column, it is returned as a Null value. On import, if a column has mixed data types, the entire column will be cast according to the ImportMixedTypes setting. The default number of rows to be checked is 8. Values are of type REG_DWORD.
ImportMixedTypes	Can be set to MajorityType or Text. If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import. If set to Text, columns of mixed data types will be cast to Text on import. The default is Text. Values are of type REG_SZ.
AppendBlankRows	The number of blank rows to be appended to the end of a Version 3.0 or Version 4.0 worksheet before new data is added. For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data. Integer values for this setting can range from 0 to 16; the default is 0 (no additional rows appended). Values are of type REG_DWORD.
FirstRowHasNames	A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row; column names appear as F1, F2, F3, and so on. The default is 01. Values are of type REG_BINARY.
Microsoft Excel ISAM Formats

The Jet\3.0\ISAM Formats\Excel 3.0 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Excel
ExportFilter	REG_SZ	Microsoft Excel 3 (*.xls)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft Excel 3.0 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Excel 4.0 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Excel
ExportFilter	REG_SZ	Microsoft Excel 4 (*.xls)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft Excel 4.0 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Excel 5.0 folder contains the following entries, which apply to Microsoft Excel versions 5.0 and 7.0.

Entry name	Type	Value
Engine	REG_SZ	Excel
ExportFilter	REG_SZ	Microsoft Excel 5-7 (*.xls)
ImportFilter	REG_SZ	Microsoft Excel (*.xls)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	1
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	01
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft Excel 5.0 file. This process will overwrite the data if exported to an existing file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft FoxPro Database Driver

When you install the Microsoft FoxPro database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft FoxPro database driver.

Microsoft FoxPro Initialization Settings

The Jet\3.0\Engines\Xbase folder includes initialization settings for the MSXB3032.dll driver, used for access to external FoxPro data sources. Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXB3032.dll

NetworkAccess=On

PageTimeout=600

INFPath=C:\DBASE\SYSTEM

CollatingSequence=ASCII

DataCodePage=OEM

Deleted=Off

Century=Off

Date=MDY

Mark=47

Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows.

Entry	Description
win32	The location of MSXB3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
NetworkAccess	A binary indicator for file locking preference. If NetworkAccess is set to 00, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument. The default value is 01. Values are of type REG_BINARY.
PageTimeout	The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type REG_DWORD.
INFPath	The full path to the .inf file directory. The Microsoft Jet database engine first looks for an .inf file in the directory containing the table. If the .inf file isn't in the database directory, it looks in the INFPath. If there is no INFPath, it uses whatever index files (.cdx or .mdx) it finds in the database directory. Values are of type REG_SZ. This entry is not written by the installation procedure.
CollatingSequence	The collating sequence for all Microsoft FoxPro tables created or opened using Microsoft Jet. Possible values are ASCII and International. The default is ASCII. Values are of type REG_SZ.
DataCodePage	An indicator of how text pages are stored. Possible settings are: • OEM OemToAnsi and AnsiToOem conversions done. • ANSI OemToAnsi and AnsiToOem conversions not done. The default is OEM. Values are of type REG_SZ.
Deleted	A binary indicator that determines how records marked for deletion are handled by the Microsoft Jet database engine. A value of 01 corresponds to the Microsoft FoxPro command SET DELETED ON and indicates never to retrieve or position on a deleted record. A value of 00 corresponds to the Microsoft FoxPro command SET DELETED OFF and indicates to treat a deleted record like any other record. The default is 00. Values are of type REG_BINARY.
Century	A binary indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions. A value of 01 corresponds to the Microsoft FoxPro command SET CENTURY ON and a value of 00 corresponds to the Microsoft FoxPro command SET CENTURY OFF. The default is 00. Values are of type REG_BINARY.
Date	The date formatting style to use in cases where date-to-string functions are used in index expressions. The possible settings for this entry, which corresponds to the Microsoft FoxPro SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD. The default is MDY. Values are of type REG_SZ.
Mark	The decimal value of the ASCII character used to separate date parts. The default depends on the Date setting as follows: • "/" (American, MDY) • "." (ANSI) • "/" (British, French, DMY) • "." (German) • "-" (Italian) • "/" (Japan, YMD) • "-" (USA) A value of 0 specifies that the system should use the separator usually associated with the selected date format. The default is 0. Values are of type REG_DWORD.
Exact	A binary indicator for string comparisons. A value of 01 corresponds to the Microsoft FoxPro command SET EXACT ON. A value of 00 corresponds to the Microsoft FoxPro command SET EXACT OFF. The default is 00. Values are of type REG_BINARY.
FoxPro ISAM Formats

The Jet\3.0\ISAM Formats\FoxPro 2.0 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	Microsoft FoxPro 2.0 (*.dbf)
ImportFilter	REG_SZ	Microsoft FoxPro (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	Microsoft FoxPro Index (*.idx; *.cdx)
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft FoxPro 2.0 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\FoxPro 2.5 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	Microsoft FoxPro 2.5 (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	Microsoft FoxPro Index (*.idx; *.cdx)
CreateDBOnExport	REG_BINARY	00
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft FoxPro 2.5 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\FoxPro 2.6 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	Microsoft FoxPro 2.6 (*.dbf)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
IndexFilter	REG_SZ	Microsoft FoxPro Index (*.idx; *.cdx)
CreateDBOnExport	REG_BINARY	00
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft FoxPro 2.6 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\FoxPro 3.0 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	Microsoft FoxPro 3.0 (*.dbf)
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	01
CreateDBOnExport	REG_BINARY	00
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft FoxPro 3.0 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\FoxPro 3.0 folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Xbase
ExportFilter	REG_SZ	Microsoft FoxPro 3.0 (*.dbc)
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	00
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Jet 2.x Database Engine Driver

When you install the Microsoft Jet 2.x Engine database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You must use the Registry Editor to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Jet Engine database driver.

Note  The installation procedure writes only one setting (win32) to the Jet\3.0\Engines\Jet 2.x folder; this is the only valid setting in this folder.

Microsoft Jet Engine Initialization Settings

The Jet\3.0\Engines\Jet 2.x folder contains a single initialization setting for the Microsoft Jet database engine.

win32=<pathname>\MSRD2X32.dll

The Microsoft Jet database engine uses the following entry to determine the path to the database engine driver.

Entry	Description
win32	Location of the database engine driver (.dll). The pathname is determined at the time of installation. Values are of type REG_SZ.
Additional initialization settings for the Microsoft Jet database engine are contained in the Jet\3.0\Engines\Jet 2.x\ISAM folder. Before you can add any of the following values to the registry, you must create the ISAM folder under the Jet\3.0\Engines\Jet 2.x folder.

To create the new folder, open the Jet\3.0\Engines\Jet 2.x folder in the Registry Editor and click Add Key on the Edit menu. In the Key Name: edit box, type ISAM and click OK. The Registry Editor creates a new folder below the Jet\3.0\Engines\Jet 2.x folder.

Note  If you are using Windows NT, the Add Key dialog box also contains an edit box for the registry key class; you can leave this setting blank.

Typical initialization settings for the entries in the Jet\3.0\Engines\Jet 2.x\ISAM folder are shown in the following example.

PageTimeout=5

LockedPageTimeout=5

CursorTimeout=5

LockRetry=20

CommitLockRetry=20

MaxBufferSize=512

ReadAheadPages=16

IdleFrequency=10

The following entries are used to configure the Microsoft Jet database engine.

Entry	Description
PageTimeout	The length of time between when data that is not read-locked is placed in an internal cache and when it's invalidated, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). Values are of type REG_DWORD.
LockedPageTimeout	The length of time between when data that is read-locked is placed in an internal cache and when it's invalidated, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). Values are of type REG_DWORD.
CursorTimeout	The length of time a reference to a page will remain on that page, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). This setting applies only to databases created with version 1.x of the Microsoft Jet database engine. Values are of type REG_DWORD.
LockRetry	The number of times to repeat attempts to access a locked page before returning a lock conflict message. The default is 20 times; LockRetry is related to CommitLockRetry, which is described below. Values are of type REG_DWORD.
CommitLockRetry	The number of times the Microsoft Jet database engine attempts to acquire a lock on data to commit changes to that data. If the Microsoft Jet database engine cannot acquire a commit lock, changes to the data will be unsuccessful. The number of attempts the Microsoft Jet database engine makes to get a commit lock is directly related to the LockRetry value. For each attempt made to acquire a commit lock, the Microsoft Jet database engine will make as many attempts as specified by the LockRetry value to acquire a lock. For example, if CommitLockRetry is set to 20 and LockRetry is set to 20, the Microsoft Jet database engine will try to acquire a commit lock as many as 20 times; for each of those attempts, the Microsoft Jet database engine will try to acquire a lock as many as 20 times, for a total of 400 attempts. The default value for CommitLockRetry is 20. Values are of type REG_DWORD.
MaxBufferSize	The size of the database engine internal cache, measured in kilobytes (K). MaxBufferSize must be a whole number value between 9 and 4096, inclusive. The default is 512. Values are of type REG_DWORD.
ReadAheadPages	The number of pages to read ahead when performing sequential scans. The default is 16. Values are of type REG_DWORD.
IdleFrequency	The amount of time, in 100 millisecond units, that Microsoft Jet will wait before releasing a read lock. The default is 10 units or one second. Values are of type REG_DWORD.
Microsoft Jet Engine ISAM Formats

The Jet\3.0\ISAM Formats\Jet 2.x folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Jet 2.x
OneTablePerFile	REG_BINARY	00
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
IsamType	REG_DWORD	0
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Jet 3.0 Database Engine

The following sections describe initialization settings for the Microsoft Jet 3.0 database engine. These registry settings must be added by the user or by your application; the Microsoft Jet 3.0 setup program does not write default values to the \HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\3.0\Engines\Jet folder.

Microsoft Jet Engine Initialization Settings

The Jet\3.0\Engines\Jet folder contains initialization settings for the Microsoft Jet database engine. Before you can add any of the following values to the registry, you must create the Jet folder under the Jet\3.0\Engines folder.

To create the new folder, open the Jet\3.0\Engines folder in the Registry Editor and click Add Key on the Edit menu. In the Key Name: edit box, type Jet and click OK. The Registry Editor creates a new folder below the Jet\3.0\Engines folder.

Note  If you are using Windows NT, the Add Key dialog box also contains an edit box for the registry key class; you can leave this setting blank.

Typical settings for the entries in the Jet\3.0\Engines\Jet folder are shown in the following example.

PageTimeout=5000

LockRetry=20

MaxBufferSize=

Threads=3

UserCommitSync=Yes

ImplicitCommitSync=No

ExclusiveAsyncDelay=2000

SharedAsyncDelay=0

SystemDB=<pathname>\System.mdb

The Microsoft Jet database engine uses the following entries.

Entry	Description
PageTimeout	The length of time between when data that is not read-locked is placed in an internal cache and when it's invalidated, expressed in milliseconds. The default is 5000 milliseconds or 5 seconds. Values are of type REG_DWORD.
LockRetry	The number of times to repeat attempts to access a locked page before returning a lock conflict message. The default is 20. Values are of type REG_DWORD.
MaxBufferSize	The size of the database engine internal cache, measured in kilobytes (K). MaxBufferSize must be an integer value greater than or equal to 512. The default is based on the following formula: ((TotalRAM in MB - 12 MB) / 4) + 512 KB For example, on a system with 32 MB of RAM, the default buffer size is ((32 MB - 12 MB) / 4) + 512 KB or 5632 KB. To set the value to the default, set the registry key to MaxBufferSize= Values are of type REG_DWORD.
Threads	The number of background threads available to the Jet database engine. The default is 3. Values are of type REG_DWORD.
UserCommitSync	Specifies whether the system waits for a commit to finish. A value of Yes instructs the system to wait; a value of No instructs the system to perform the commit asynchronously. The default is Yes. Values are of type REG_SZ.
ImplicitCommitSync	Specifies whether the system waits for a commit to finish. A value of No instructs the system to proceed without waiting for the commit to finish; a value of Yes instructs the system to wait for the commit to finish. The default is No. Values are of type REG_SZ.
ExclusiveAsyncDelay	Specifies the length of time, in milliseconds, to defer an asynchronous flush of an exclusive database. The default value is 2000 or 2 seconds. Values are of type REG_DWORD.
SharedAsyncDelay	Specifies the length of time, in milliseconds, to defer an asynchronous flush of a shared database. The default value is 0. Values are of type REG_DWORD.
SystemDB	Specifies the full pathname and filename of the system database. The default is the appropriate pathname followed by the filename System.mdb. Values are of type REG_SZ.
CompactByPKey	Specifies that when you compact tables they are copied in primary-key order, if a primary key exists on the table. If no primary key exists on a table, the tables are copied in base-table order. A value of 0 indicates that tables should be compacted in base-table order; a non-zero value indicates that tables should be compacted in primary-key order, if a primary key exists. The default value is non-zero. Values are of type REG_DWORD. Note:  This setting only applies to compacting databases created with the Microsoft Jet database engine version 3.0; when you compact databases created with the Microsoft Jet database engine version 2.x, the data is always copied in the order of the base table.
Microsoft Jet Engine ISAM Formats

The Jet\3.0\ISAM Formats folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Jet 3.0
ExportFilter	REG_SZ	Microsoft Access (*.mdb)
ImportFilter	REG_SZ	Microsoft Access (*.mdb)
CanLink	REG_BINARY	00
OneTablePerFile	REG_BINARY	00
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a Microsoft Access database. This process will overwrite the data if exported to an existing file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Paradox Database Driver

When you install the Paradox database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Paradox database driver.

Paradox Initialization Settings

The Jet\3.0\Engines\Paradox folder includes initialization settings for the MSPX3032.dll driver, used for access to external Paradox data. Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSPX3032.dll

PageTimeout=600

CollatingSequence=ASCII

DataCodePage=OEM

ParadoxUserName=Kimberly

ParadoxNetPath=P:\PDOXDB

ParadoxNetStyle=4.X

The Microsoft Jet database engine uses the Paradox folder entries as follows.

Entry	Description
win32	The location of MSPX3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
PageTimeout	The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type REG_DWORD.
CollatingSequence	The collating sequence for all Paradox tables created or opened using Microsoft Jet. Possible values are ASCII, International, Norwegian-Danish, and Swedish-Finnish. The CollatingSequence entry must match the collating sequence used when the Paradox table was built. The default is ASCII. Values are of type REG_SZ.
DataCodePage	An indicator of how text pages are stored. Possible settings are: • OEM OemToAnsi and AnsiToOem conversions done. • ANSI OemToAnsi and AnsiToOem conversions not done. The default is OEM. Values are of type REG_SZ.
ParadoxUserName	The name to be displayed by Paradox if a table is locked by the Paradox ISAM and an interactive user accessing the data from Paradox (rather than the ISAM) attempts to place an incompatible lock. This entry isn’t added if the computer isn't on a network. Values are of type REG_SZ. Note: If you indicate a ParadoxUserName, you must also specify a ParadoxNetPath and a ParadoxNetStyle or you’ll receive an error when trying to access external Paradox data..
ParadoxNetPath	The full path to the directory containing the PARADOX.NET file (for Paradox 3.x) or the PDOXUSRS.NET file (for Paradox 4.x). This entry isn’t added if the computer isn’t on a network. Usually, you need to change the initial setting (added by the Setup program), which is a best guess at where the file might be. The full ParadoxNetPath (including the drive letter) must be consistent for all users sharing a particular database (directory). Values are of type REG_SZ. Note: If you indicate a ParadoxNetPath, you must also specify a ParadoxUserName and a ParadoxNetStyle or you’ll receive an error when trying to access external Paradox data.
ParadoxNetStyle	The network access style to use when accessing Paradox data. Possible values are: • 3.x • 4.x (Note that Paradox 3.x users can’t set this to 4.x or the driver will use the wrong locking method. Paradox 5.0 users must use the 4.x ParadoxNetStyle setting to ensure proper locking behavior.) This entry isn’t added if the computer isn’t on a network. This entry should correspond to whatever version of Paradox the users in the group are using. It must be consistent for all users sharing a particular database (directory). The default is 4.x. Values are of type REG_SZ. Note: If you indicate a ParadoxNetStyle, you must also specify a ParadoxUserName and a ParadoxNetPath or you’ll receive an error when trying to access external Paradox data.
Paradox ISAM Formats

The Jet\3.0\ISAM Formats\Paradox 3.x folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Paradox
ExportFilter	REG_SZ	Paradox 3 (*.db)
ImportFilter	REG_SZ	Paradox (*.db)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a Paradox 3 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Paradox 4.x folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Paradox
ExportFilter	REG_SZ	Paradox 4 (*.db)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextExport	REG_SZ	Export data from the current database into a Paradox 4 file. This process will overwrite the data if exported to an existing file.
The Jet\3.0\ISAM Formats\Paradox 5.x folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Paradox
ExportFilter	REG_SZ	Paradox 5 (*.db)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	0
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextExport	REG_SZ	Export data from the current database into a Paradox 5 file. This process will overwrite the data if exported to an existing file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Text Data Source Driver

When you install the Text Data Source database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Text Data Source database driver.

Text Data Source Initialization Settings

The Jet\3.0\Engines\Text folder includes initialization settings for the MSTX3032.dll driver, used for external access to text data files. Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSTX3032.dll

MaxScanRows=25

FirstRowHasNames=False

CharacterSet=OEM

Format=TabDelimited

Extensions=none,asc,csv,tab,txt

ExportCurrencySymbols=Yes

The Microsoft Jet database engine uses the Text folder entries as follows.

Entry	Description
win32	The location of MSTX3032.dll. The full pathname is determined at the time of installation. Values are of type REG_SZ.
MaxScanRows	The number of rows to be scanned when guessing the column types. If set to 0, the entire file will be searched. The default is 25. Values are of type REG_DWORD.
FirstRowHas Names	A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row. The default is 01. Values are of type REG_BINARY.
CharacterSet	An indicator of how text pages are stored. Possible settings are: • OEM OemToAnsi and AnsiToOem conversions done. • ANSI OemToAnsi and AnsiToOem conversions not done. The default is OEM. Values are of type REG_SZ.
Format	Can be any of the following: TabDelimited, CSVDelimited, Delimited (<single character >). The single-character delimiter in the Delimited format can be any single character except a double quotation mark ("). The default is CSVDelimited. Values are of type REG_SZ.
Extensions	The extension of whatever files are to be browsed when looking for text-based data. The default is txt, csv, tab, asc. Values are of type REG_SZ.
ExportCurrencySymbols	A binary value that indicates whether the appropriate currency symbol is included when currency fields are exported. A value of 01 indicates that the symbol is included. A value of 00 indicates that only the numeric data is exported. The default is 01. Values are of type REG_BINARY.
Text Data Source ISAM Formats

The Jet\3.0\ISAM Formats\Text folder contains the following entries.

Entry name	Type	Value
Engine	REG_SZ	Text
ExportFilter	REG_SZ	Text Files (*.txt; *.csv; *.tab; *.asc)
ImportFilter	REG_SZ	Text Files (*.txt; *.csv; *.tab; *.asc)
CanLink	REG_BINARY	01
OneTablePerFile	REG_BINARY	01
IsamType	REG_DWORD	2
IndexDialog	REG_BINARY	00
CreateDBOnExport	REG_BINARY	00
ResultTextImport	REG_SZ	Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink	REG_SZ	Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport	REG_SZ	Export data from the current database into a text file. This process will overwrite the data if exported to an existing file.
Note   When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Accessing Databases on CD-ROM with DAO

If you need to provide users with a Microsoft Jet database on CD-ROM or other read-only media, the Jet engine does not attempt to distinguish whether the media is read-only (unlike a share, which can be read-only for some users and read-write for others). Therefor, the database should be opened using the read-only and exclusive options. Other users can still access the CD-ROM in the same way.


Accessing External Databases with DAO

Your application can access data from external databases, which can include other Microsoft Jet databases (.mdb), ODBC-based databases, or installable ISAM databases.

The most efficient way to access external data is to link an external table to an existing Jet database. Linking a table creates a reference to the external table and saves it in your Microsoft Jet database. This stored link keeps a record of the database table's structure. None of the external database data is stored in the .mdb file.

You can create dynaset-type and snapshot-type Recordset objects with linked tables.

Linking tables to an existing Jet engine database

To link an external table to your database, you can write code as outlined in the following steps:

1.	Create variables for the Database and TableDef objects you are going to modify:

Dim tdf As TableDef, dbs As Database

2.	Use the OpenDatabase method to open the existing database:

Set dbs = OpenDatabase("C:\Database\Mydb.mdb")

3.	Create a TableDef object for the external table:

Set tdf = dbs.CreateTableDef("Customer Detail")

 	4.	Set the TableDef object properties to refer to the linked table:

tdf.Attributes = dbAttachedODBC

tdf.Connect = "ODBC;DSN=SSRVR1;UID=Fred;PWD=RHS;DATABASE=SQLDB;"

tdf.SourceTableName = "CustDetail"

5.	Append the TableDef object to the TableDefs collection with the Append method. This step actually creates the object links in the database file.

Note   Although this method is the most efficient way to access data stored in other Microsoft Jet databases, ODBC-based databases, and ISAM databases, it does not support SQL PassThrough queries. If your application must support SQL PassThrough, please refer to Using SQL PassThrough.

Each of the data sources available through Data Access Objects (DAO) sometimes have specific considerations for using data. The following topics can provide additional detailed information on using these data sources.

Accessing Data in a dBASE Database with DAO

Accessing Data in a Lotus Spreadsheet with DAO

Accessing Data in a Microsoft Excel Worksheet or Workbook with DAO

Accessing Data in a Microsoft FoxPro Database with DAO

Accessing Data in a Microsoft Jet Database with DAO

Accessing Data in a Paradox Database with DAO

Accessing Data in a Text Document with DAO

Accessing Data in ODBC Databases with DAO

If your application expects particular behavior from the external database driver, you may want to review the registry settings for the driver to make sure they meet your application's needs. The following topics can provide additional detailed information on initializing each driver.

Initializing the dBASE Database Driver

Initializing the Lotus Driver

Initializing the Microsoft Excel Driver

Initializing the Microsoft FoxPro Database Driver

Initializing the Jet Engine Driver

Initializing the Paradox Database Driver

Initializing the Text Data Source Driver

Initializing the Microsoft ODBC Database Driver


Building SQL Statements in Code

This topic discusses how to create a Structured Query Language (SQL) statement to manipulate data in your database. SQL statements can be used to retrieve data from one or more tables, to add, update or delete records, or to execute stored procedures or foreign SQL statements on external databases.

Overview

To let your application generate context-sensitive SQL queries or adapt existing queries in ways not ordinarily supported by parameter queries, your application can build an SQL query in code. Parameter queries can only accept SQL arguments that substitute for the values in the SQL statement; you cannot substitute table names, expressions, or operators in parameter queries.

If you don't expect the Microsoft Jet database engine query to be changed by your code, create a permanent query in Microsoft Access or a QueryDef in your application code. QueryDef objects execute faster and can be executed by other applications that use your Jet engine database. In many cases, you can create a parameter query that has all of the advantages of an SQL QueryDef and also accepts parameters that can be substituted at run time.

Determine the SQL Dialect

To create an SQL statement in your application, first determine the target of the query. If it is the Jet engine, you need to use Jet engine syntax. Otherwise, use the syntax required by the backend query processor. If you are working with a database engine other than the Jet engine (like Microsoft SQL Server), your only option to pass parameters to SQL statements or stored procedures may be to build the SQL statement in code.

When working with the Jet engine, the easiest way to create SQL statements is to use Microsoft Access to create a sample that closely approximates the syntax needed by your application. After you've created and tested the sample, save the query as a QueryDef object or use the Clipboard to paste it into your application.

Construct the Query

When your application is ready to modify the SQL sample, use the concatenation operator (&) to join portions of the sample SQL with variables in your application. Avoid using the plus operator (+), which implies addition of the arguments. If your substituted arguments must be bounded by quotation marks in the SQL query, your logic must provide quotation marks on both ends of the string.

Arguments passed from the user that contain single quotation marks ( ' ) or double quotation marks ( " ) may break the quotation pairing in your SQL statement. You can use either single or double quotation marks to delimit SQL strings, as long as they are used in matched pairs. Strings that contain an apostrophe ( ' ) must use two single quotation marks to denote an apostrophe, as in the following example, which illustrates how to pass the string "Gardener's Handbook".

qdfPassThrough.SQL = "SELECT * FROM dbo_titles" & _

" WHERE Title = 'Gardener''s Handbook'"

Note that the code example uses the string concatenation character (&) and the line continuation character ( _ ) to break up longer lines of code. This syntax can make your application code easier to read, but isn't supported or necessary with SQL statements.

Tip   Watch out for spaces before and after the arguments provided, especially when you break your string into more than one line. Without the space before the WHERE clause, the SQL statement would read: SELECT * FROM dbo_titlesWHERE Title = 'Gardener''s Handbook'.


Choosing a Field Data Type with DAO

Every field in a table must have a defined data type. The Field object data type determines the kind and range of values that can be entered in a field, the amount of storage space available in the field, and the amount of space allocated in the database to store the data.

Choose a variable type best suited to contain the data used in the database. Conversions are done automatically wherever possible. Your code triggers a trappable error if you attempt to save a value that doesn't conform to the limitations of the field.

For Field objects declared as type dbText, you also need to set the Size property that indicates the length of the longest String to be saved in the field. All other types of Field objects have their Size property set automatically.

The table below lists the types of data, the constant used in the Type property, and their uses.

Data Type	Constant	Use for

Text	dbText	Text and numbers, such as names and addresses, phone numbers, and postal codes. A Text field can contain from 0 to 255 characters. You must set the Size property to the maximum length of your text when you declare a field as type Text.

Memo	dbMemo	Lengthy text and numbers, such as comments or explanations. A Memo field's size is limited by the maximum size of the database.

Number	(various)	Numerical data on which you intend to perform mathematical calculations, except calculations involving money. See the following table for a further explanation of number fields.

Date/Time	dbDate	Dates and times. These values are stored in a combined field [image] the date is always stored with the time.

Currency	dbCurrency	Used where a field contains monetary values. Don't use the Number data type for currency values because numbers to the right of the decimal may be rounded during calculations. The Currency data type maintains a fixed number of digits to the right of the decimal. Set the Field object Type property to dbCurrency for currency fields.

Counter	dbLong	Sequential numbers automatically inserted by the Microsoft Jet database engine. Set the dbAutoIncrement flag in the Field object Attributes property. Numbering begins with 1. The Counter data type makes a good primary key field. If you want to establish a primary key/foreign key relationship between two tables using a counter field, make sure that the foreign key column data type is also defined as Long. You can also set (or read) dbRandomIncrField in a new Field object's Attributes property to indicate that a counter field is generated with random numbers. (This is valid only on fields that are counters.)

Yes/No	dbBoolean	Yes/No, True/False, On/Off, or fields that contain only one of two values.

OLE Object	dbLongBinary	Objects created in other programs using the OLE protocol.

Binary Image	dbLongBinary	Any value that can be expressed in binary up to 1.2 gigabytes in size. This type is used to store pictures, files or other raw binary data.

Number types	Use for

dbBoolean	Binary values of 0 or 1.

dbByte	Positive values from 0 to 255. Stored in Byte variables.

dbInteger	Values from –32,768 to +32,767. Stored in Integer variables.

dbLong	–2,147,483,648 to 2,147,483,647 (about 2.1 GB). Stored in Long variables.

dbSingle	–3.402823E38 to 1.401298E–45 for negative numbers and 1.401298E–45 to –3.402823E38. Stored in Single variables.

dbDouble 	1.79769313486232E308 to 4.94065645841247E–324 for negative values and 4.94065645841247E–324 to 1.79769313486232E308 for positive values. Stored in Double variables.

Notes

Select the appropriate data type for each field. For example, you usually define most fields in a table of names and addresses as Text fields. Even a phone number field that contains only digits should be defined as a Text field. Reserve the Number data type for fields on which you want to perform calculations.

You can't index fields with the data types Long Binary, Memo, or OLE Object.

Limitations

The records you define must fit on the 2K pages supported for Jet databases by the Jet database engine. Each Field object you include in the table definition counts toward this 2K total, including Binary and Memo fields. The amount stored for Binary and Memo fields, however, is only 14 bytes per non-null field, and only 1 byte for null fields, as the actual data for these fields is stored on additional pages. The amount of data committed to each text field isn't set until you actually store data in the field. Generally, you can "overcommit" a data page by defining more text fields than there would be room for, but no more than about 2K of actual data can be stored in a record. For example, you can define 15 250-byte text fields in a record as long as the total number of characters stored is less than about 2K. See the definitions for each of the data types to find out how much space each type of field uses.


Creating a Database with DAO

This topic discusses how to create a database in code.

A database file can contain a number of data access objects, and some of those objects can contain other objects or collections of objects. Before you create a database, you should have a good idea about what information will be stored in your database and what kinds of tables, fields, and indexes you'll need to store and track that information.

External ISAM Databases

An external database is one where the actual data is stored in another file or database management system, not in a Microsoft Jet database (.mdb file). In most cases, external ISAM databases are stored in a named disk directory. To create a new ISAM FoxPro database, you would use the Windows Explorer or the DOS MkDir statement to create a new directory. To open this database, specify the path of the directory as the database name. Individual tables are referenced by their filenames.

External ODBC Databases

The Microsoft Jet database engine can't create external ODBC databases. This can be accomplished from your application, however, by using the SQL PassThrough option with the Execute method. For Microsoft SQL Server installations, for example, the system administrator (SA) user can use the OpenDatabase method to open the Master database with the SA password and then pass the required Transact SQL Statements to the SQL Server using the Execute method. To add tables to the database from your application, you need to open it directly using a Connect string as discussed in the following section.

Example

You can write code to create and modify the structure of a database. After you plan the structure of your tables, use these basic steps to create a database:

1.	Declare a variable for the Database object you want to create:

Dim dbs As Database

2.	Use the Workspace object's CreateDatabase method to create an empty database file and Database. The CreateDatabase method sets the locale (language) used and the Jet database version.

Note   If you are working with an existing external database, use the CreateDatabase method to set the Database object variable.

' General language locale; create Microsoft Jet version 3.0 database.

Set dbs = Workspaces(0).CreateDatabase("MyNewDbs.mdb", _

dbLangGeneral, _

dbVersion30)

3.	Define each table in the database. To do this, you first need to define the fields for each table. Create the database tables and fields using the following steps:

a.	Use the Database object's CreateTableDef method to create a TableDef object for each table. This method names the database table:

Dim tdf as TableDef

Set tdf = dbs.CreateTableDef("Customers")

b.	Use the new TableDef object's CreateField method to create a Field object for each field. The example creates and names three fields. Be sure to set the Size property for text fields and any other required attributes before the field is appended:

Dim fld as Field

Set fld = tdf.CreateField("CustID",dbLong)

' This is a counter field.

fld.Attributes = dbAutoIncrField

tdf.Fields.Append fld

Set fld = tdf.CreateField("CustName",dbText,25)

tdf.Fields.Append fld

Set fld = tdf.CreateField("Picture",dbLongBinary)

tdf.Fields.Append fld

c.	Append the new TableDef to the Database object's TableDefs collection. This is the step that actually creates the object in the database file. Once appended, you can't make further changes to the appended field. You can, however, add new fields or delete existing field definitions.

dbs.TableDefs.Append tdf

4.	You can optionally create one or more Index objects for each table using the TableDef object's CreateIndex method. After you create each Index object, create a Field object to describe which fields are used as keys. For one of the indexes, set the Primary property to True. If you want the Jet database engine to prevent duplicates in the table based on a chosen index, set the Unique property to True:

a.	Use the TableDef object's CreateIndex method to create an Index object.

Dim idx as Index

Set idx = tdf.CreateIndex("CustomerIndex")

b.	Use the Index object's CreateField method to create a Field object for each field in the table that is a component of the key. Append each Field object to the Index object's Fields collection:

Set fld = Idx.CreateField("CustID")

fld.Primary = True

idx.Fields Append fld

c.	Append each Index object to the Indexes collection of the TableDef object with the Append method. A table can have no indexes or several indexes.

tdf.Indexes.Append idx


Creating Parameter Queries with DAO

In situations where your application executes the same query repeatedly, it is more efficient to create a stored QueryDef object that contains the query SQL statement. Queries stored in the database execute faster and can be used by anyone with access to the database.

If your application needs to alter WHERE clause arguments in a query, you can also add a PARAMETERS clause to your query that permits the Microsoft Jet database engine to substitute values into the query at run time. Before running Parameter queries, your application must substitute values for each of the parameters as stored in the Parameters collection of the Querydef object.

To create a parameter query

1.	Create a PARAMETERS clause string that includes a ParameterName and DataType for each parameter. Don't use the field name alone as the ParameterName, because duplicating it may cause problems. You can, however, include the field name within the ParameterName.

If you are working with a database accessed by Microsoft Access, the ParameterName is used as a prompt string. Keep this in mind if you expect Microsoft Access users to use this query.

The following shows a typical PARAMETERS clause:

SQL$ = "PARAMETERS [Product Wanted] TEXT; [Size] LONG "

2.	Create a SELECT statement that fetches the needed fields and incorporates the named parameters into the WHERE clause. In the example below, the parameters are used to filter the query to return only selected products of a specified size. Note that the parameter [Product Wanted] is substituted by the Jet engine during execution of the query at run time.

SQL$ = SQL$ & "SELECT DISTINCTROW * " & _

" FROM Vendors" & _

" WHERE ((Vendors.ProductID =[Product Wanted]) " & _

" AND (Vendors.Size = [Size])) " & _

" WITH OWNERACCESS OPTION; "

3.	Create a named QueryDef object with your SQL statement.

Dim qdf as QueryDef

Set qdf = CreateQueryDef("Find Vendors", SQL$)

4.	You are now ready to set the QueryDef object parameters. First, you need to gain access to the QueryDef object. You can either use the QueryDef object just created, or reference the stored QueryDef object from the QueryDefs collection. The example shows two different types of addressing; either is acceptable. You can also address the parameters by their ordinal number.

Dim qdfParmQD as QueryDef

Set qdfParmQD = dbs.QueryDefs("Find Vendors")

qdfParmQD("Product Wanted") = "Salmon"	' Note two ways to

qdfParmQD!Size = 16	' address parameters.

5.	You are now ready to execute the procedure. Because this query returns records, you need to create a Recordset object to capture the result set.

Dim rst as Recordset

Set rst = qdfParmQD.OpenRecordset()

Notes

You can use the BETWEEN...AND SQL operators in a parameter query to retrieve a range of values. For example, you can enter BETWEEN [Low price] AND [High price] in the WHERE clause to fetch a list of products within a certain range of prices.

You can create a parameter query with the LIKE operator that allows the user to provide wildcard characters. For example, if you enter LIKE [Enter the first letter]&*, the user can enter B to display all values that start with the letter B.


Customizing Windows Registry Settings for Data Access Objects

Unless your application can work correctly with the default functionality of the Microsoft Jet database engine, you must change the settings in the Windows Registry to suit your needs. The Windows Registry can also be used to tune the operation of the installable ISAM and ODBC driver. If your application can't accept the default behavior of the drivers, which is loaded from the shadow settings, you must create an entry in the Windows Registry for your Microsoft Jet client application and override the default settings to get the appropriate behavior from your application.

Note   You should not directly modify settings in the ISAM Formats subfolder. If you need to make any modifications to these settings, use the setup program provided with the drivers to ensure that these changes are correctly made.

To register Jet database engine settings for your application, create a Jet portion in your application's registry tree to manage the settings for the Jet database engine. Then, add any values you want to specify to the registry tree. If you have supplied any values in the Engines subfolder, Microsoft Jet loads those settings when the application starts. Any values not entered in your client application's registry tree are loaded from shadow settings.

For example, to register Jet database engine settings for an application named "Soccer.exe" you would create a client registry tree similar to the following:

HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines

In the registry tree, you could override the default settings for the Jet database engine ISAM by setting the PageTimeout to a lower value (the default value is 5, or 500 milliseconds). By setting PageTimeout to 1, your application will invalidate data in the internal cache in 100 milliseconds. To register this new setting for your application, set the HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines\PageTimeout value to 1. When you start the application, the Jet database engine instance associated with Soccer.exe is configured with all settings in HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines. Any settings not indicated in your client's registry tree will be loaded from the Jet database engine shadow settings for the client machine. For example, if the client application registry folder HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines\Jet contains only one entry that sets the value of PageTimeout to 1, only that setting will be changed from the default values found in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.0 during application initialization.

You can also edit the Windows Registry to specify:

Settings used for interaction with Microsoft FoxPro, Paradox, and dBASE databases. See Initializing the Paradox Database Driver, Initializing the Microsoft FoxPro Database Driver, and Initializing the dBASE Database Driver.

Settings used by Microsoft ODBC for interaction with SQL databases. See Initializing the Microsoft ODBC Database Driver.

Settings that affect how the Jet database engine reads and saves data. See Initializing the Microsoft Jet Engine Database Driver.


Data Access Objects Overview

Data Access Objects (DAO) enable you to use a programming language to access and manipulate data in databases, and to manage databases, their objects, and their structure.

Microsoft Jet Database Engine

You can use Data Access Objects to manipulate databases in either the native Jet database engine .mdb format or in other installable ISAM database formats including Fox, dBASE, Excel, Paradox, and delimited Text. In addition, you can use the Microsoft Jet database engine to access Microsoft SQL Server and any other database that can be accessed with an ODBC driver using the same DAO code.

Data Access Objects

You can declare new data access object variables for any of the object types using the Dim and Set statements. For example, the following code creates object variables for a Database object, a dynaset-type Recordset object, and a Field object:

Dim dbs As Database, rst As Recordset, fld As Field

Set dbs = OpenDatabase("Biblio.mdb")

Set rst = dbs.OpenRecordset("Authors", dbOpenDynaset)

Set fld = rst.Fields("Au_ID")

Data access objects have a default collection or property. For example, the default collection of a Recordset object is the Fields collection and the default property of a Field object is the Value property. You can simplify your code by taking advantage of these defaults. For example, the following code sets the value of the PubID field in the current record:

Set rst = dbs.OpenRecordset("Publishers", dbOpenDynaset)

rst!PubID=99

You can use object variables and other DDL features to modify your database structure. For example, you can add a new Field object to an existing table with the following code:

Dim dbs As Database, tdf as TableDef, fld As Field

Set dbs = OpenDatabase("Biblio.mdb")	' Open database.

Set tdf = dbs.TableDefs("Authors")

Set fld = tdf.CreateField("Address", dbText, 20)

tdf.Fields.Append fld	' Append to TableDef fields.

This code creates a new object variable for a Field object and adds it to a TableDef object with the Append method. Because a TableDef object contains the definition of a table, the table now has a field named Address for entering data. In much the same way, you can create new tables and new indexes.

DBEngine and Workspace Objects

All data access objects are derived from the DBEngine object, which represents the Jet database engine. When your application starts, the Jet engine creates a default DBEngine.Workspace object that can be referenced through the Workspaces collection (Workspaces(0)). You can open additional Workspace objects as needed. Each Workspace object has a user ID and password associated with it.

Note   Unless you need to manipulate databases that have security enabled or create a separate transaction scope, you don't need to reference the DBEngine or Workspace objects. The default DBEngine.Workspaces(0) object is assumed if it isn't specifically referenced. For example, to open a database using DAO and create a table-type Recordset object, you can write the following code:

Dim dbs as Database, rst as Recordset

Set dbs = OpenDatabase("Biblio.mdb")

Set rst = dbs.OpenRecordset("Titles")

All Database objects opened against a Workspace object share a common transaction scope. That is, when you use the BeginTrans method on a database, it applies to all other open databases opened in the Workspace object. In the same way, using the CommitTrans method against one database applies to all other databases opened in the Workspace object.

Security

You can restrict access to one or more .mdb databases or their tables using security settings established and managed by the Jet database engine. In your code, you can establish Group and User objects to define the scope and level of permissions available to individual users on an object-by-object basis. For example, you can establish permissions for a specific user to provide read-only access to one table and full access to another.

Important   Before you can establish or alter any security settings, you need to gain access to the system database file associated with the .mdb database. This file can only be created by a special utility included with Microsoft Access version 2.0 or later. Without this file, your application can't activate security for a .mdb database.


Selecting a Recordset Type for Data Access Objects

This topic discusses the types of Recordset objects available and how each type affects the performance and operation of your application.

Tables, Dynasets, and Snapshots

The Microsoft Jet database engine provides three kinds of recordsets: tables, which are actual database tables; dynasets, which can be updated; and snapshots, which cannot.

Table-type recordsets are available for any Microsoft Jet or installable ISAM database. You cannot create a table-type recordset from an ODBC database. When you use this type of Recordset object, it is as if you are directly opening the table.

A dynaset-type recordset provides an updatable set of records by fetching the key values that uniquely identify each of the rows. The data from the bookmarked rows is fetched only when needed to populate the Table or Query datasheet view. Using key values speeds the retrieval operation and minimizes network traffic, especially when browsing large tables. Memo and OLE objects are not retrieved unless they need to be displayed.

Use a dynaset-type recordset when you are dealing with a large number of records (more than 500) or when the recordset you're using contains Memo or OLE Object fields.

A snapshot-type recordset cannot be updated. The data contained in each of the rows is fetched when you create the recordset. Creating a snapshot-type recordset can be much faster with small tables that do not contain a large number of columns and do not include Memo fields and OLE objects. (Although this is a performance concern, Jet table snapshots containing Memo or OLE fields will not retrieve the data into the snapshot until it is actually referenced.) You can also improve the retrieval speed of snapshot-type recordsets by making sure you are returning only the columns you need.

Use a snapshot-type recordset when you don't need to update the data in the source table, when you are dealing with a small number of records (fewer than 500), or when the Recordset object you're using doesn't contain Memo or OLE Object fields.

Using Forward-Only Snapshot Recordsets

By default, snapshot-type Recordset objects provide bidirectional scrolling capability. If you do not need this capability (for example, if you only need to make a single pass through the records), you can use the dbForwardOnly flag to specify a forward-only recordset. This allows the result set is to be copied to a non-scrollable buffer area.


Positioning the Current Record Pointer with DAO

Whenever you work with Recordset objects, the record that can be examined or modified is referred to as the current record. Only the current record is available for modification. This topic discusses how to position the current record pointer to specific records in an open Recordset object. For more detailed information, search the online index for the individual methods or see the See Also list.

You need to use one of the programmatic methods discussed below to reposition the pointer. In some cases, no current record exists and references to it trigger a trappable error. For example, the current record is invalid if you:

Delete the current record or all records in a Recordset object.

Create a Recordset object with no records.

Move beyond the beginning (BOF property) or end (EOF property) of the Recordset object.

A Seek method or one of the Find methods has failed and the NoMatch property is True.

You can position the current record in five ways. All of these techniques depend on the type of Recordset object you are using, whether bookmarks are supported, and if the Recordset object has a valid index. See the table shown later in this topic to determine which methods work with which type of Recordset object.

The Move Methods

The Move methods (Move, MoveFirst, MoveLast, MovePrevious, MoveNext) reposition the current record pointer based on its current position (Move, MoveNext, and MovePrevious), based on the beginning (MoveFirst) or end (MoveLast) of the Recordset object, or relative to a bookmark (Move). Using the Move methods, you can position the current record pointer beyond either end of the Recordset object, making it invalid.

Search Based on Criteria

Use the Seek method or one of the Find methods (FindFirst, FindLast, FindNext, FindPrevious) to reposition based on criteria you provide. The Seek method works only with table-type Recordset objects, while the Find methods work only with dynaset and snapshot-type Recordset objects. If the record you are searching for doesn't exist, the NoMatch property is set to True.

Using a Bookmark

If the Recordset object you are working with supports bookmarks, you can move the current record pointer to any specific record by setting the Recordset object's Bookmark property to a valid bookmark. To position to the record most recently added or changed, use the bookmark in the Recordset object's LastModified property. If you clone a working Recordset object, you can use bookmarks from the clone to position the current record pointer in the working Recordset object. The Move method can also be used to position based on a bookmark plus or minus an offset from that position.

Using Record Numbers

Although relational database applications shouldn't depend on record numbers, several properties permit positioning within a Recordset object based on the ordinal number of the record. Note that a record number isn't assigned to individual records in the database, but is created when a Recordset object is built. For this reason, they can be different each time the Recordset object is created. Ordinal record numbers are assigned from 1 to the value of the RecordCount property.

You can use the AbsolutePosition property to position to a specific record based on its ordinal number, or the PercentPosition property to move to the record closest to the percentage value provided. For example, in a Recordset object with 50 records, using the PercentPosition property with an argument of 10 positions to the 5th record.

Note that the Recordset object's RecordCount property for table-type Recordset objects is set to the number of records in the table. For dynaset and snapshot-type Recordset objects, the RecordCount property is set to 0 for empty Recordset objects or to 1 for unpopulated Recordset objects. As you move the current record pointer toward the end of the Recordset object, the RecordCount property is incremented for each record visited. Using the MoveLast method on the Recordset object or its clone fully populates the Recordset object and sets the RecordCount property to the number of records in the Recordset object.

Adding and Deleting Records

Records are always added to the end of a dynaset- or snapshot-type Recordset object regardless of the order in which the Recordset object was originally created; a table-type Recordset object maintains records in the order specified by the current index. After a record is added, the current record pointer is repositioned to the record that was current before the record was added. When you need to delete records, only the current record can be deleted. After the delete is complete, the current record is invalid. You'll need to reposition it to another valid record.

Using Record Positioning Methods and Properties

Method or Property	Recordset Type	Notes
AddNew	Dynaset, table	If Updatable property is True.
Delete	Dynaset, table	If Updatable property is True.
Find methods	Dynaset, snapshot	Current record pointer moves to the first record in the Recordset object if NoMatch property is True.
Move	Dynaset, snapshot, table	Relative to current location or specific bookmark.
Move methods	Dynaset, snapshot, table	Can reposition past EOF property or BOF property, making current record invalid.
PercentPosition	Dynaset, snapshot, table	Not for forward-only scrolling snapshots.
Seek	Table	Current record pointer moves to the first record in the Recordset object if NoMatch property is True.
AbsolutePosition	Dynaset, snapshot	Not for forward-only scrolling snapshots.


Querying a Database with SQL in Code

To work with the data in a database, you can use queries to manipulate or extract data. A query either asks the database for a set of records matching specified criteria (a select query), or tells the database to perform a specified operation on a set of records that match specified criteria (an action query). In any case, you can use an SQL statement to define which records you want, and how you want them ordered and grouped.

If you use an SQL query to retrieve data, the Microsoft Jet database engine creates only a dynaset-type or snapshot-type Recordset object. After the Recordset object is built, you can use one of the Find methods to further refine the search or step through the records one at a time.

You can execute queries in several ways:

Use an SQL action query as an argument to the Execute method.

Create and execute a custom Querydef object.

Use an SQL statement as an argument to the OpenRecordset method.

Execute an existing Querydef object with the OpenRecordset method.

Using an SQL action query as an argument to the Execute method

If you need to execute an action query to perform an operation that doesn't return records, as when you insert or delete records, you can use an SQL statement as an argument to the Execute method. The Execute method can be used with an open Database object as long as the query doesn't return records.

Creating a new QueryDef object

You can set the SQL property of a QueryDef object in either of two situations:

1.	Create a complete QueryDef object in code:

Dim qdfMyQuery As QueryDef, dbs As Database, strMySQL As String

Set dbs = OpenDatabase("C:\VB\Biblio.mdb")

strMySQL = "SELECT Author FROM Authors WHERE Author LIKE 'A*'"

Set qdfMyQuery = dbs.CreateQueryDef("A Names", strMySQL)

2.	Use the QueryDef object to create a Recordset object with either of these lines of code:

Set rst = qdfMyQuery.OpenRecordset()
Set rst = dbs.OpenRecordset("A Names")

Note   You can also create parameter queries that allow you to modify parts of a query at run time without changing the query saved in the database.


Retrieving Data Using SQL and DAO

You can use SQL to query, update, and manage relational databases such as Microsoft Jet databases.

You can also use SQL statements in many places where you can enter the name of a table, query, or field. For example, you can enter an SQL statement instead of a table name when using the OpenRecordset method to create a Recordset object.

To learn more about the parts of an SQL statement, search Help for any of the Microsoft Jet database engine SQL reserved words:

SELECT fieldlist

FROM tablenames IN databasename

WHERE searchconditions

GROUP BY fieldlist

HAVING searchconditions

ORDER BY fieldlist

SQL statements can't be entered in the same way as other application programming commands. To use an SQL statement in your program, build a string containing the statement and either include it as a literal quoted argument, or as a variable in a method, statement, or function.

Because SQL statements can be very long, you might want to break them up for readability. To do this, use the line continuation character ( _ ) as shown in the following example. Note that SQL statements can't contain embedded carriage return characters, because they act as statement terminators. The following example uses a valid SQL statement.

Dim strSQL as String, rst as Recordset

strSQL = "SELECT LastName, FirstName " & _

" FROM Employees " & _

" WHERE Salary > 21000;"

Set rst = OpenRecordset(strSQL)

Note   You might want to use Microsoft Access to create queries for your application. When you create a query in the Query window, Microsoft Access creates the equivalent SQL statement. You can view or edit this statement by choosing SQL from the View menu in the Microsoft Access Query window or by clicking the SQL View button. After you create and test the statement, save the query as a QueryDef object or use the Clipboard to paste it into your application.


Using Counter Fields with DAO

In situations where your table records need a value to act as a unique record identifier, the Microsoft Jet database engine can be programmed to use a Counter field that automatically provides a unique value for this purpose. There are two types of counters: sequential and random. Sequential counters start at 1 and increase by 1 for each record added. Random counters assign random values to each record as it is added.

To create a new sequential Counter field with this feature, set the dbAutoIncrField bit in the Attributes property of a Field object, and assign the Long data type to the Type property. To create a new random Counter field, set the Type property to Long and set the DefaultValue property with the string “GenUniqueID(),” which calls a function that generates a random number each time a record is added to the table.

The Jet database engine automatically calculates a unique Long Integer for these Field objects and supplies it when the record is written to the table with the Update method. Your code doesn't need to supply this value. If you choose to supply the value in your code, it must be a valid (and unique) Long Integer greater than or equal to zero.

To determine the number assigned to a specific record once the data is written to disk, execute the Edit method. If you are using a sequential counter, you can determine the current record count with the following code.

Dim rst as Recordset

rst.AddNew

Debug.Print rst("MyCounterColumn")

In this example, MyCounterColumn is the column name of the table's counter column. The value that appears is the next number that will be assigned to the counter.

Note   When your code establishes relationships to Counter fields, be sure to use the Long data type on related foreign key fields.


Using Named Arguments

In some cases, arguments for methods, functions, statements, and procedures can be coded using the argument name instead of positional arguments. This topic discusses how to write code for and pass these arguments.

Note   Named arguments aren't supported universally in Visual Basic. If you aren't sure whether a method, function, or statement supports named arguments, consult Help or the Object Browser on the specific topic.

Coding

Postional arguments are specified by coding arguments in a specific order. Named arguments use the argument name followed by :=. For example, to supply False to an argument named "READONLY", use: READONLY:=False. Each named argument is listed in the object library under the method, function, or statement. Press the F2 key to open the object library dialog.

Using named arguments doesn't eliminate the need to specify arguments where required, but it does allow you to place them in any order. Separate all arguments by commas, regardless of style.

To determine specific names to use for each argument, paste the object into your code from its object library entry. For example, the entry for the OpenDatabase method appears as follows.

OpenDatabase(Name:=, [Exclusive]:=, [ReadOnly]:=, [Connect]:=)

Using positional arguments, the OpenDatabase method can be coded in a number of ways. For example, where only the database name is supplied, use the following code.

Set dbs = OpenDatabase("MyDbs.mdb")

Or, where the Name, Exclusive, Readonly, and Connect arguments are all supplied, use the following code.

Set dbs = OpenDatabase("MyDSN", _

False, _

False , _

"ODBC;UID=Vicky")

The OpenDatabase method can also be coded by replacing positional arguments with equivalent named arguments. For example, where only the database name is supplied, use the following code.

Set dbs = OpenDatabase(Name:="MyDbs.mdb")

Or, where the Name, Exclusive, Readonly, and Connect arguments are all supplied, use the following code.

Set dbs = OpenDatabase(Name:="MyDSN", _

Exclusive:=False, _

ReadOnly:=False, _

Connect:="ODBC;UID=Vicky")

Or, where the Name, Exclusive, Readonly, and Connect arguments are supplied, but in a different order, use the following code.

Set dbs = OpenDatabase(Connect:="ODBC;UID=Vicky", _

Name:="MyDSN", _

ReadOnly:=False, _

Exclusive:=False")


Obsolete Features in DAO

Microsoft Access versions 1.x and 2.0 and Microsoft Visual Basic version 3.0 used earlier versions of the Microsoft Jet Database Engine and Data Access Objects.  Several DAO objects, methods, and statements in those earlier versions are considered “obsolete.”

The following is a list of Data Access Object methods, properties, objects, and functions that have been replaced by more powerful, flexible, and easy-to-use features. Each obsolete feature in the list has a corresponding replacement feature.

Obsolete feature	Replacement feature
All CreateDynaset methods	OpenRecordset method
All CreateSnapshot methods	OpenRecordset method
All ListFields methods	Fields collection
All ListIndexes methods	Indexes collection
CompactDatabase statement	DBEngine.CompactDatabase method
CreateDatabase statement	DBEngine.CreateDatabase method
DBEngine.FreeLocks method	DBEngine.Idle method
DBEngine.SetDefaultWorkspace method	DBEngine.DefaultUser and DBEngine.Password properties
DBEngine.SetDataAccessOption method	DBEngine.IniPath property
Database.BeginTrans method	Workspace.BeginTrans method
Database.CommitTrans method	Workspace.CommitTrans method
Database.Rollback method	Workspace.Rollback method
Database.DeleteQuerydef method	Delete method
Database.ExecuteSQL method	Execute method
Database.ListTables method	Tabledefs collection
Database.OpenQuerydef method	Querydefs collection
Database.OpenTable method	OpenRecordset method
Index.Fields property	Index.Fields collection
OpenDatabase statement	DBEngine.OpenDatabase method
Querydef.ListParameters method	Parameters collection
Snapshot object	Recordset object
Dynaset object	Recordset object
Table object	Recordset object


Locking Behavior in Multiuser Applications

Version 3.0 of the Microsoft Jet database engine contains a number of improvements to locking behavior, which include support for multithreading and implicit transactions. This new behavior differs from the default behavior in Microsoft Jet version 2.x in some key areas that might affect existing Microsoft Jet applications. This topic describes the similarities and differences in the two locking models and suggests coding strategies that enhance the performance of applications [image] new and existing [image] by taking advantage of the new model.

Using Explicit Transactions

Application code that uses explicit transactions won't be affected by changes in the locking strategy from Microsoft Jet version 2.x to Microsoft Jet version 3.0. Explicit transactions are those that use a BeginTrans method followed by a conditional expression that determines the success of operations in the transaction. If all operations in the transaction succeed, the application code calls the CommitTrans method to save the data to the database; if any operation fails, the application code cancels the effects of all operations by calling the Rollback method.

Implicit Transactions with SQL DML Commands

SQL Data Manipulation Language (DML) commands, such as UPDATE, INSERT, or DELETE, cause the Jet database engine to start an explicit transaction to process the commands. Because these commands frequently involve several rows of data, they are often referred to as "bulk" or "set" operations. This behavior is the same in both versions of the Jet database engine.

Multiuser Programming Considerations without Transactions

In an environment where multiple users are allowed concurrent access to data, Microsoft Jet version 2.x and Microsoft Jet version 3.0 behave differently in the areas of locking behavior, which specifies when locked records and pages are released, and latency, which determines when a user sees the results of other users' additions or changes.

Locking behavior in Microsoft Jet version 3.0 is improved by reducing the number of times data is read from and written to disk. In version 2.x, data was written after each Recordset.Update method; in version 3.0, however, locks on the page containing individual records remain in place until the Microsoft Jet engine has accumulated enough data to fill the data cache or until two seconds (or the number of seconds specified in the Jet Engine SharedAsyncDelay registry key for your application) have elapsed since the start of the implicit transaction and the ImplictCommitSync registry setting is set to No. These registry settings are described in Initializing the Jet Engine Driver.

Concurrent access to data in a multiuser application is reduced compared with version 2.x code as locks are usually held by an individual user for a longer period of time. Although this locking strategy appears to reduce concurrency, it can increase performance in certain types of applications by reducing the number of read, write, and lock operations that would otherwise occur. Any delays in existing application code can be minimized by adding explicit transaction code to emulate the Microsoft Jet 2.x locking behavior. The following example illustrates this technique.

Example

This code example illustrates a typical scenario that relies on the Microsoft Jet 3.0 locking strategy. To emulate Microsoft Jet 2.x locking behavior, add the Workspace.BeginTrans method before opening the record buffer for editing with Recordset.Edit method and add the Workspace.CommitTrans method after the Recordset.Update method to force Microsoft Jet to write the edits to disk.

Set rst = OpenRecordset("SELECT * FROM Customer", dbOpenDynaset)
While NOT rst.EOF
wrk.BeginTrans
rst.Edit
rst.CustId = CustId
rst.CLstNm = CLstNm
rst.Update
wrk.CommitTrans

rst.MoveNext
WEnd

Latent Changes

Another change in Microsoft Jet version 3.0 involves the amount of time it takes for changes made by one user to appear to other users. Because this behavior is also related to the delay in writing data to disk, the solution is the same.

To make sure data is written to disk at the time you expect, you can modify your code to use explicit transactions to emulate Microsoft Jet 2.x locking behavior, as in the previous example. This solves the latency problem and ensures that no updates are pending after the transaction has been committed. This also ensures that your changes will be visible to all users immediately after the transaction has completed.

Considerations for Handling Errors

In Microsoft Jet version 2.x, errors that occurred during update operations caused an immediate transfer to the error handler, which allowed the application to determine which record was being processed when the error occurred. In Microsoft Jet version 3.0, critical errors that occur due to the inability to write data to disk are handled at the time Microsoft Jet tries to commit the data or write the contents of the cache to disk. Because it is possible in a multithreaded environment for one thread to attempt to write data to disk while another thread continues to edit records, you must be aware of the possibilities for delayed error reporting and prepare your application's error handling routines accordingly. If you need to emulate the error handling behavior in Microsoft Jet 2.x, just use the technique described previously for committing updates.

Note   Errors resulting from implicit updates (caused by writes from the filled cache) or explicit transaction commit (CommitTrans) operations are handled in the same way.


Populating Recordsets and Counting Records with DAO

This topic discusses how to get an accurate count of the records in each type of Recordset object when the Recordset object is populated. Each of the three types of Recordset objects is associated with specific record-counting behavior. Table-type Recordset objects exhibit the simplest behavior; as soon as an application opens this type of Recordset object, the total count of records (that is, all members of the Recordset object) is known. Snapshot- and dynaset-type Recordset objects, however, are populated based on criteria you specify when you create the Recordset object. Therefore, the membership of the Recordset object cannot be determined until all records satisfying the selection criteria have been added.

Determining Recordset Membership in a Snapshot- or Dynaset-type Recordset Object

Because these types of Recordset objects are populated by a query, membership in snapshot- or dynaset-type Recordset objects is fixed when the current row pointer is positioned to the last eligible row. It is only then that the Recordset object is considered to be fully populated. To force immediate population, you can execute a MoveLast method against the Recordset object, or move the current record pointer to (that is, visit) each record in the Recordset object.

In some cases, a Recordset object can be fully populated immediately following its creation. Depending on the way the Jet database engine creates it, or how you phrase the SQL query, the number of populated rows can vary from a minimum of 0, when the Recordset object is empty, to the total number of rows returned by the query.

Multiuser Considerations

In a multiuser environment, more than one user can add, delete, or change the records that qualify or disqualify records as members of the Recordset object until it is fully populated. This means that any Recordset object can contain records retrieved over a relatively long period of time.

Until you execute a MoveLast method, or otherwise position to the end of the Recordset object, the number of qualified members in your Recordset object can't be determined because it isn't fixed. For this reason, the RecordCount property is set to zero for an empty Recordset object or to the number of records actually fetched by the Jet database engine. After you move the current record pointer to the last record, no further members are included, and the RecordCount property reflects the total number of records in the Recordset object, regardless of the changes that other users make.

When other users delete records from the base table or tables, your Recordset object's RecordCount property remains unchanged until you move to a deleted record. At this point, a trappable error occurs and the current record is no longer valid. When your code positions to records changed by other users, these changes are available to your table-type and dynaset-type Recordset object, but not to your snapshot-type Recordset object.

Determining Current Record Position

You can use the Bookmark property to set or return the location of the current record relative to the RecordCount property value. You can also use the PercentPosition or AbsolutePosition property in some scenarios to achieve similar results.

Note   When working with external ODBC databases that can only handle one active statement, the connection to the external server is held open until the Recordset object is fully populated. In addition, this connection can't be reused for other queries until the last result set is completely fetched. For these reasons, your code should attempt to fully populate the Recordset object as quickly as possible if you have many open Recordset objects.


Initializing the Microsoft ODBC Database Driver

The following sections describe initialization settings for the Microsoft ODBC database driver. These registry settings must be added by the user or by your application; the ODBC Driver Setup program does not write default values to the \HKEY_LOCAL_MACHINE\Software\Microsoft\Access\7.0\Jet\3.0\Engines\ODBC folder.

Microsoft ODBC Driver Initialization Settings

The \HKEY_LOCAL_MACHINE\Software\Microsoft\Access\7.0\Jet\3.0\Engines\ODBC folder contains initialization settings for the Microsoft Jet database engine. Before you can add any of the following values to the registry, you must create the ODBC folder under the Jet\3.0\Engines folder.

To create the new folder, open the Jet\3.0\Engines folder in the Registry Editor and click Add Key on the Edit menu. In the Key Name: edit box, type ODBC and click OK. The Registry Editor creates a new folder below the Jet\3.0\Engines folder.

Note  If you are using Windows NT, the Add Key dialog box also contains an edit box for the registry key class; you can leave this setting blank.

Typical settings for the entries in the Jet\3.0\Engines\ODBC folder are shown in the following example.

LoginTimeout=20

QueryTimeout=60

ConnectionTimeout=600

AsyncRetryInterval=500

AttachCaseSensitive=0

AttachableObjects='TABLE','VIEW','SYSTEM TABLE','ALIAS','SYNONYM'

SnapshotOnly=0

TraceSQLMode=0

TraceODBCAPI=0

DisableAsync=0

JetTryAuth=1

PreparedInsert=0

PreparedUpdate=0

FastRequery=0

The Jet database engine uses the ODBC entries as follows.

Entry	Description
LoginTimeout	The number of seconds a login attempt can continue before timing out. The default is 20 (values are of type REG_DWORD).
QueryTimeout	The number of seconds a query can run (total processing time) before timing out. The default is 60 (values are of type REG_DWORD).
ConnectionTimeout	The number of seconds a cached connection can remain idle before timing out. The default is 600 (values are of type REG_DWORD).
AsyncRetryInterval	The number of milliseconds between polls to determine if the server is done processing a query. This entry is used for asynchronous processing only. The default is 500 (values are of type REG_DWORD).
AttachCaseSensitive	An indicator of whether to match table names exactly when linking. Values are 0 (link the first table matching the specified name, regardless of case) and 1 (link a table only if the name matches exactly). The default is 0 (values are of type REG_DWORD).
AttachableObjects	A list of server object types to which linking will be allowed. The default is: 'TABLE', 'VIEW', 'SYSTEM TABLE', 'ALIAS', 'SYNONYM' (values are of type REG_SZ).
SnapshotOnly	An indicator of whether Recordset objects are forced to be of snapshot type. Values are 0 (allow dynasets) and 1 (force snapshots only). The default is 0 (values are of type REG_DWORD).
TraceSQLMode	An indicator of whether the Jet database engine will trace SQL statements sent to an ODBC data source in SQLOUT.txt. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD). This entry is interchangeable with SQLTraceMode.
TraceODBCAPI	An indicator of whether to trace ODBC API calls in ODBCAPI.txt. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD).
DisableAsync	An indicator of whether to force synchronous query execution. Values are 0 (use asynchronous query execution if possible) and 1 (force synchronous query execution). The default is 0 (values are of type REG_DWORD).
JetTryAuth	An indicator of whether to try using the Microsoft Access user name and password to log in to the server before prompting. Values are 0 (no) and 1 (yes). The default is 1 (values are of type REG_DWORD).
PreparedInsert	An indicator of whether to use a prepared INSERT statement that inserts data in all columns. Values are 0 (use a custom INSERT statement that inserts only non-Null values) and 1 (use a prepared INSERT statement). The default is 0 (values are of type REG_DWORD). Using prepared INSERT statements can cause Nulls to overwrite server defaults and can cause triggers to execute on columns that weren't inserted explicitly.
PreparedUpdate	An indicator of whether to use a prepared UPDATE statement that updates data in all columns. Values are 0 (use a custom UPDATE statement that sets only columns that have changed) and 1 (use a prepared UPDATE statement). The default is 0 (values are of type REG_DWORD). Using prepared UPDATE statements can cause triggers to execute on unchanged columns.
FastRequery	An indicator of whether to use a prepared SELECT statement for parameterized queries. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD).


Accessing Data in ODBC Databases with DAO

Data Access applications can connect to any database with an ODBC driver. Before any application can access an ODBC database, the ODBC drivers must be installed and a Data Source Name (DSN) created using the Windows Control Panel or the RegisterDatabase method. Whenever you refer to an ODBC database, this DSN is used. It contains the linkage information used by the ODBC drivers and the Microsoft Jet database engine to establish a connection to the database.

Once you have installed the proper drivers and created a DSN, you can use the DSN to connect to an external ODBC-based table. There are two ways to connect to ODBC database tables:

Link an ODBC database table or view to a Microsoft Jet database and use the OpenRecordset method to access the table.

Create a QueryDef object that references an ODBC database.

The most efficient way to access ODBC database tables is to link the external table to an existing Jet database. Linking a table creates a reference to the external table and saves it in your Jet database. This stored link keeps a record of the database table's structure. None of the external database data is stored in the .mdb file. You can create dynaset-type and snapshot-type Recordset objects with linked tables.

Linking ODBC tables to an existing Jet database

To link an ODBC-based table to your database, you can write code as outlined in the following steps:

1.	Create variables for the Database and TableDef objects you are going to modify.

Dim tdf As TableDef, dbs As Database

2.	Use the OpenDatabase method to open the existing database.

Set dbs = OpenDatabase("C:\Database\Mydb.mdb")

3.	Create a TableDef object for the external table.

Set tdf = dbs.CreateTableDef("Customer Detail")

 	4.	Set the TableDef object properties to refer to the linked table.

tdf.Attributes = dbAttachedODBC

tdf.Connect = "ODBC;DSN=SSRVR1;UID=Fred;PWD=RHS;DATABASE=SQLDB;"

tdf.SourceTableName = "CustDetail"

5.	Append the TableDef object to the TableDefs collection with the Append method. This step actually creates the object links in the database file.

Creating a QueryDef object that references an ODBC database

Although linking is the most efficient way to access data stored in ODBC tables, it does not support SQL pass through queries. In cases where you need to execute SQL statements that can only be executed on the ODBC database, like Transact SQL statements on Microsoft SQL Server, or to execute stored procedures, create a QueryDef object whose Connect property contains an ODBC connect string. The Jet database engine can return multiple result sets and messages from stored procedures when you use a QueryDef object to execute the procedure.

When using ODBC databases, the LockEdits property is always False. The Jet database engine defaults to optimistic locking. You can update ODBC database tables only if a unique key exists for the table. If you need to use and update an external temporary table, create an index for it before linking it.

You can set an upper limit on the time that the Jet database engine takes to open an ODBC database by setting the LOGINTIMEOUT argument in the Connect string. You can also limit the time the Jet database engine takes to execute an ODBC query by setting the QueryTimeout property of the Database object or the ODBCTimeout property of the QueryDef object. When any of these preset times expire, a trappable error occurs.

To perform many of its operations more quickly on Microsoft SQL Server systems, the ODBC driver may create one or more stored procedures in your working database. If your program terminates abnormally, these procedures may remain on the server. Generally, it is safe to remove these procedures manually once you determine they are not being used.

For more information on SQL pass through queries, refer to Using SQL PassThrough.

Note   adjust the parameters used by the Jet database engine when working with ODBC databases, create a special table, MSysConf, on each ODBC database that you expect to access from your Jet database engine application. For more information, please refer to Using the MSysConf Table with SQL Databases.


Using SQL PassThrough with DAO

SQL pass through queries permit your application to bypass the Microsoft Jet database engine query processor and route foreign-dialect SQL statements to an external database server such as SQL Server.

This technique is used to pass single or multiple SQL commands, stored procedures, or other SQL statements to an external database server to be executed. Whenever you specify an SQL pass through query, the Jet database query processor is bypassed, but its recordset processor is used to create and manage the result sets that may be generated by your query.

Typical Uses

An SQL pass through query can be used to force query processing to be executed on an external database engine. For example, you can use an SQL pass through query to:

Execute a stored procedure.

Run an SQL query using foreign syntax or return more than one set of results.

Create a new database, table, or index on an external server.

Create or manage Triggers, Defaults, Rules, or stored procedures.

Maintain user accounts or perform other System Administrator tasks.

Run maintenance operations like Microsoft SQL Server's DBCC.

Execute multiple INSERT or UPDATE statements in a single batch.

Implementation

You can create SQL pass through queries by creating a QueryDef object or you can construct the query in code. In most cases, you will use a QueryDef object, which allows more control over the query. However, two cases exist in which constructing or modifying an SQL pass through query in code is more appropriate: when you are converting existing SQL code for use with linked tables and when your SQL query requires parameters.

If your SQL pass through query returns a result set, the Jet database engine creates a snapshot-type Recordset object for the set.

This version of the Jet database engine supports use of SQL pass through queries by permitting your code to set the SQL property of the QueryDef object to contain non-Jet database engine SQL syntax.

Note   You can't set parameters for the query using the Parameters collection of the QueryDef object. To build SQL queries that require parameters, you need to construct or modify the SQL pass through query in code using the following technique.

To create and execute an SQL pass through query from code

1.	Open the Jet database that is linked to the SQL tables you want to access.

2.	Set the Database object's Connect property to point to the server against which you want to run your SQL pass through query.

3.	Use the Execute method or the OpenRecordset method with the dbSQLPassThrough flag to run the query, as in the following example.

Set dbs = OpenDatabase("Salary.mdb" _

dbs.Connect = "ODBC;dsn=Accounting;uid=Dagny;"& _

pwd=Bandit;database=Payroll;"

dbs.Execute "Update UPDATE Employees SET Salary = Salary * 1.1;", _

dbSQLPassThrough

To create an SQL pass through QueryDef object

1.	Use the CreateQueryDef method to create a QueryDef object using only a name argument. If you specify an SQL argument, you can't use foreign SQL syntax [image] it must comply with Jet database engine SQL syntax. To create a temporary QueryDef object that isn't automatically saved in the database, use the CreateQueryDef method without the name argument.

2.	Set the Connect property of the QueryDef object to a valid connect string to inform the Jet database engine that this is an SQL pass through query. From this point forward, the Jet database engine doesn't attempt to parse the SQL property.

3.	Set the SQL property of the QueryDef object to the SQL statement to be executed. Be sure to use SQL syntax as dictated by the external server.

4.	If you expect your query to return one or more sets of records (rows), set the ReturnsRecords property of the QueryDef object to True to inform the Jet database engine to expect records (rows) back from the query. This forces the Jet database engine to create a Recordset object for each set of results. If you don't set the ReturnsRecords property to True for a query that returns records, a trappable error results.

For example, the following code creates an SQL pass through QueryDef object that executes a stored procedure called MultipleResultSets.

Dim rst As Recordset, dbs As Database, qdf As QueryDef

Set dbs = Workspaces(0).OpenDatabase("Mydb.mdb")

Set qdf = dbs.CreateQueryDef("My QD")

qdf.Connect = "odbc;dsn=MyDSN;uid=Chrissy;pwd=Champ;database=TestDB;"

qdf.SQL = "MultipleResultSets"

qdf.ReturnsRecords = True

To execute the SQL pass through QueryDef object

1.	Use the OpenRecordset method to execute the stored QueryDef object so the first (and only the first) set of results is available.

Set rst = dbs.OpenRecordset("My Qd", dbOpenSnapshot)

To process any additional result sets of an SQL pass through QueryDef object

1.	Create and execute a temporary QueryDef object that executes a Jet SQL make table query using SELECT INTO statement syntax. The Jet database engine creates one new table for each set of results and stores them in your database. If more than one user executes this code at the same time when using a shared database, the applications may generate table name collisions.

The SELECT INTO statement query doesn't return records, but it builds one or more tables to store the results from the QueryDef object. By not providing a name to the CreateQueryDef method, the Jet database engine doesn't store a new QueryDef object in the database.

Set qdf = dbs.CreateQueryDef("")

qdf.SQL = "SELECT [My QD].* INTO Result FROM [My QD];"

qdf.Execute

2.	Create and process each of the resulting tables that contain the results of the QueryDef object using the OpenRecordset method.

Set rst = dbs.OpenRecordset("Result")

.	' Process the results of the query.

.

.

3.	Repeat the process for each of the result sets. Unless you know how many there are, you must query the TableDefs collection to see how many result set tables were created. Note that the Jet database engine numbers each subsequent table sequentially. In this case, the table name Result contains the first set of results, Result1 contains the second, and so on.

' Get second set of results.

Set rst = dbs.OpenRecordset("Result1")

.	' Process results.

.

.

' Get Third set of results.

Set rst = dbs.OpenRecordset("Result2")

.	' Process results.

.

.

rst.Close	' Close Recordset object; you are done with it.

4.	Remove the tables used to store the results of your query.

dbs.Recordsets.Delete "Result"

dbs.Recordsets.Delete "Result1"

dbs.Recordsets.Delete "Result2"


Using the MSysConf Table to Administer SQL Database Access through DAO

If you are administering an SQL database with front-end applications that use the Microsoft Jet database engine, you can create a table in your SQL database named MSysConf to help you control communication between the two applications. You can add this table to each SQL database you expect to access. Without the MSysConf table in your SQL database, the Jet database engine uses all of the default settings as described below.

The MSysConf table can disable the feature that enables users to store the login ID and password for an attached SQL database locally. You can also use the MSysConf table to set the number of rows of data that are retrieved at one time and the number of seconds of delay between each retrieval.

The Structure of the MSysConf Table

The SQL database table MSysConf should have the following structure.

Column name	Data type	Allows Null?
Config	A data type that corresponds to a 2-byte integer	No
chValue	VARCHAR(255)	Yes
nValue	A data type that corresponds to a 4-byte integer	Yes
Comments	VARCHAR(255)	Yes
Note   If the data source you're working with is case-sensitive, use the table and column names exactly as shown.

All users must have permission to use the SELECT statement on this table; only the system administrator should have INSERT/UPDATE/DELETE permission.

The Data in the MSysConf Table

There are three valid records in the MSysConf table. The table below shows the values you should enter in the Config and nValue field. The other columns are reserved for future use; their contents are ignored in this release.

Config	nValue	Meaning
101	0	Don't allow local storage of the login ID and password in attachments.
101	1	(Default) Allow local storage of the login ID and password in attachments.
102	D	D is the delay, in seconds, between each retrieval (default: 10 seconds).
103	N	N is the number of rows retrieved (default: 100 rows).
Notes

Setting a higher delay time decreases network traffic, but increases the amount of time that read-locks are held on data (if the server uses read-locks).

If you create an MSysConf table, it must be set up properly or you can't connect to the SQL database table at all.


Adding Replication to Your Application Using DAO

Database replication is the process of copying a database so that two or more copies stay synchronized in terms of data and objects. Each copy of the database is called a replica, and each contains an identical set of tables, queries, forms, reports, macros, and modules. Replicas that belong to the same replica set can exchange updates of data or replicated objects. This exchange is called synchronization.

Applications

Database replication is useful for:

Sharing data among offices.

Sharing data among dispersed users.

Making server data more accessible.

Distributing application updates.

Backing up data.

Building Replication Into an Application

Many of the replication functions available through Microsoft Access and through Windows Briefcase can be handled in code. You begin by creating a Microsoft Jet database, as you would for any application, and then converting the database into a replicable form. Prior to converting the database, you can designate which tables, queries, forms, reports, macros, or modules in the database you want to keep from being included in all subsequent replicas. For more information, see Converting a Database Into a Replicable Form With DAO and Keeping Objects Local When Replicating a Database With DAO.

After the database has been replicated, you can make additional replicas for other users or computers. Any new tables, queries, forms, reports, macros, or modules created at each replica remain at that replica. However, you can make any of these objects replicable by changing the object's Replicable property. For more information on making additional replicas, see Making Additional Replicas With DAO and Making Objects Replicable or Local With DAO.

After you have made additional replicas and started using them, you can synchronize changes to the replicas. The Synchronize method allows you to merge the data changes made at one replica with changes made at other replicas in the set. Synchronization also updates the other replicas with any changes made to the Design Master. The Microsoft Jet database engine supports multiple masters for changing data but only a single master for changing the design of the database. The synchronization process might produce a conflict between two replicas where users changed the same record. You can resolve these conflicts by reviewing the system table that stores them or by writing a custom resolution program. For more information on synchronization, see Synchronizing Replicas With DAO and Resolving Synchronization Conflicts With DAO.

By default, the first replica in the set is the Design Master. As user or system requirements change, you can make another replica the Design Master. If you are unable to use the Design Master because it is damaged or corrupted, you can recover by making your own replica the new Design Master. For more information on Design Masters, see Moving Design-Master Status to Another Replica With DAO and Making a Replica the Design Master With DAO.


Keeping Objects Local When Replicating a Database With DAO

When a database is converted to a replicable form, all the objects in the database are converted to replicated objects unless you indicate otherwise. Prior to converting your database, you can create and set the KeepLocal property on the object you do not want made replicable. For example, if your database had a table containing confidential personnel information, such as salaries, you can set that table's KeepLocal property to "T" to keep it local while all other objects are made replicable when the database is made replicable.

Warning   The object on which you are setting the KeepLocal property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to keep local. You must directly set the property for each object.

If you set the KeepLocal property and the property has not already been appended or inherited, you will receive an error. In the following example, the program sets the KeepLocal property to "T" and includes an error handler in case it receives the "property does not exist" error. If called, the error handler both appends and sets the property.

Sub SetKeepLocalEvenIfInherited(objParent As Object)

Const errPropNotFound = 3270

On Error GoTo KeepLocalPropHndlr

objParent.Properties("KeepLocal").Value = "T"

Exit Sub

KeepLocalPropHndlr:

If (Err = errPropNotFound) Then

objParent.Properties.Append objParent.CreateProperty _

("KeepLocal", dbText, "T")

Else

' user-defined error handler

End If

Resume Next

End Sub

The KeepLocal property cannot be applied to objects after they have been converted into a replicable form. To make a replicable object local, set the object's Replicable property to "F".

If you have set a relationship between two tables in your database, the KeepLocal property must be set the same for both tables. Both tables must be local or both must be replicable. If the property is not set the same at both tables, the conversion will fail.

Note   The KeepLocal and Replicable properties can be used only if your application has Microsoft Access with Briefcase Replication installed.


Converting a Database Into a Replicable Form With DAO

You can convert your database by setting the Replicable property of your database to "T". For example, to make your database replicable, use the following code.

Sub MakeDBReplicable(strTargetDB)

Dim dbs As Database

' Open database in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strTargetDB, True)

' Create property called "Replicable" and set to "T"

dbs.Properties.Append dbs.CreateProperty("Replicable", dbText, _

"T")	' Makes the DB replicable.

dbs.Close

End Sub

During the conversion process, the Microsoft Jet database engine maintains all the property settings of your original database.

Notes

There is no method to make a database non-replicable once it is made replicable. Setting the Replicable property to "F" has no effect.

The Replicable property can be used only if your application has Microsoft Access with Briefcase Replication installed.


Making Additional Replicas With DAO

When you convert your database by setting the Replicable property, it becomes the Design Master and the first member in the replica set. From the Design Master, you make the next replica. Subsequent replicas can be made from the Design Master or from another replica in the set using the MakeReplica method. For example, you might use the following code to make a replica of your database.

Sub MakeAdditionalReplica(strReplicableDB, strNewReplica)

Dim dbs As Database

set dbs = DBEngine(0).OpenDatabase(strReplicableDB)

dbs.MakeReplica strNewReplica, "First Replica of" & _

strReplicableDB,dbRepMakeReadOnly

dbs.Close

End Sub

If you include the dbRepMakeReadOnly constant, the replicated elements of the newly created replica cannot be modified. Otherwise, users are able to make changes to the data in the new replica. As the Microsoft Jet database engine creates the new replica, all property settings of the source replica are included in the new replica.

Notes

Making a new replica copies all of the replicable objects and properties from the source replica to the new replica. All attached (linked) tables are copied, but the path to an attached table may no longer be accurate because of the new replica's location on the network. Be sure to test the new replica to determine if a new path needs to be established for any of the attached tables.

The Replicable property and MakeReplica method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Synchronizing Replicas With DAO

You can keep the replicas synchronized using the Synchronize method. By specifying a target database filename, you can synchronize one replica with another replica in the set. Various types of exchanges can be performed including export, import, and bidirectionals. If no argument is provided, the exchange is bidirectional (import and export). For example, you might use the following code to do a two-way synchronization between replicas:

Sub SynchronizeDBs(strDBName, strSyncTargetDB)

Dim dbs As Database

set dbs = DBEngine(0).OpenDatabase(strDBName)

'Synchronize replicas (bidirectional exchange).

dbs.Synchronize strSyncTargetDB, dbRepImpExpChanges

dbs.Close

End Sub

When the Microsoft Jet database engine synchronizes replicas, it always synchronizes design changes first. (Both replicas must be at the same design level before data can be exchanged.)

Note   The Synchronize method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Making Objects Replicable or Local With DAO

When a database is converted to a replicable form, all the objects in the database are converted to replicable objects unless their KeepLocal property was set to "T". After a database is made replicable, all new objects created with the Design Master or any other replica in the set are treated as local objects. Local objects remain at the replica where they were created and are not propagated around the replica set. Each time you make a new replica in the set, all the replicable objects at the source replica are included in that new replica, but none of the local objects are included.

There may be instances when you create a new object at a replica and want to change it from local to replicable so that all users could have it. To change an object from local to replicable, you must either create the object at, or import it into, the Design Master. After the object is part of the Design Master, you must set the object's Replicable property to "T".

Warning   The object on which you are setting the Replicable property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to make replicable. You must directly set the property for each object.

If you set the Replicable property and the property has not already been appended or inherited, you will receive an error. In the following example, the program sets the Replicable property to "T" and includes an error handler in case it receives the "property does not exist" error. If called, the error handler both appends and sets the property.

Sub SetReplicableEvenIfInherited(objParent As Object)

Const errPropNotFound = 3270

On Error GoTo ReplicablePropHndlr

objParent.Properties("Replicable").Value = "T"

Exit Sub

ReplicablePropHndlr:

If (Err = errPropNotFound) Then

objParent.Properties.Append objParent.CreateProperty _

("Replicable", dbText, "T")

Else

' user-defined error handlier

End If

Resume Next

End Sub

At the next synchronization, the newly replicable object appears at the other replicas in the set. Similarly, if you want to make a replicable object local, you set its Replicable property to "F". At the next synchronization, the object that was global is deleted at all replicas except the Design Master.

Note   The KeepLocal and Replicable properties can be used only if your application has Microsoft Access with Briefcase Replication installed.


Resolving Synchronization Conflicts With DAO

After synchronizing two replicas, you should review the database for conflicts. You can determine if a conflict has occurred for a specific table by using the ConflictTable property on the table. This property returns the name of the conflict table that contains the records for that table that conflicted during synchronization. For example, to find the name of the conflict table associated with a table in your database, to examine each record conflict, and to take action to resolve the conflict, you might use the following code:

Sub Resolve (dbs As Database)

Dim tdfTest As TableDef, rstConflict As Recordset

For Each tdfTest In dbs.TableDefs

If (tdfTest.ConflictTable <> "") Then

Set rstConflict = dbs.OpenRecordset(tdfTest.ConflictTable)

' Process each record.

rstConflict.MoveFirst

While Not rstConflict.EOF

' Do conflict resolution.

.

.

rstConflict.Delete

' Remove conflicting record when finished

rstConflict.MoveNext

Wend

rstConflict.Close

End If

Next tdfTest

End Sub

If there is no conflict table or the database is not replicated, the property returns a zero-length string.

Note   The ConflictTable property can be used only if your application has Microsoft Access with Briefcase Replication installed.


Moving Design-Master Status to Another Replica With DAO

The Design Master is the most important member in a replica set because it is the only location where you can make changes to the structure of the database. Under certain circumstances, you might need to make a replica the new Design Master and make the old Design Master a replica. For example, you might have the Design Master on your computer while another member of your development team has a replica on his or her computer. While you are on vacation, you may want the other developer to be able to make design changes to the database. As shown in the following code example, you can use the ReplicaID property to establish a new DesignMasterID and synchronize the old and new Design Masters.

Sub SetNewDesignMaster(stroldDM, strNewDM)

Dim dbs as Database, newdmdb as Database

' Open current Design Master in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strOldDM, True)

' Open database that will become the new Design Master.

Set newdmdb = DBEngine(0).OpenDatabase(strNewDM)

dbs.DesignMasterID = newdmdb.ReplicaID

dbs.Synchronize strNewDM,dbRepImpExpChanges

dbs.Close

newdmdb.Close

End Sub

You must have the current Design Master open to make a replica the new Design Master, and you must synchronize after making the change for it to take effect.

The Design Master is a read/write replica. If you make a replica that is designated read-only the new Design Master, it is made read/write and the old Design Master becomes a read-only replica.

If the Design Master is erased or corrupted, you can make any replica the new Design Master; but there must be only one Design Master at a time.

Note   The ReplicaID property can be used only if your application has Microsoft Access with Briefcase Replication installed.


Making a Replica the Design Master With DAO

The Design Master is the most important member in a replica set because it is the only location where you can make changes to the structure of the database. Under extreme circumstances—for example, the original Design Master becomes damaged or corrupted—you can use the ReplicaID property to set the DesignMasterID property at the current replica and make that replica the new Design Master for the set. However, setting the DesignMasterID property to the ReplicaID property setting for the current replica, when there is already another Design Master, might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

Warning   Never create a second, concurrent Design Master in a replica set. The existence of a second Design Master can result in the loss of data.

If you still need to make your replica the Design Master, synchronize all the replicas in the replica set before changing the DesignMasterID property at your replica.

You must have the replica open to make it the Design Master. The Design Master is, by definition, a read/write replica. If you make a replica that is designated read-only the Design Master, it automatically becomes read/write.

Note   The ReplicaID property can be used only if your application has Microsoft Access with Briefcase Replication installed.


AddNew Method

Creates a new record for a table-type or dynaset-type Recordset object.

Syntax

object.AddNew

The object placeholder represents the name of an open table-type or dynaset-type Recordset object to which you want to add a new record.

Remarks

The AddNew method creates a new record you can edit and add to the Recordset object named by object. This method sets the fields to Null (the default values specified for a table-type Recordset) or default values, if any.

After you modify the new record, use the Update method to save the changes and add the record to the recordset. No changes are made to the database until you use the Update method.

Caution   If you issue an AddNew and then perform any operation that moves to another record without using Update, your changes are lost without warning. In addition, if you close the object or end the procedure that declares the object or its Database object, the new record and the changes made to it are discarded without warning.

When you use AddNew and the Microsoft Jet database engine has to create a new 2K page to hold the current record, page locking is pessimistic. If the new record fits in an existing page, page locking is optimistic.

If you haven't moved to the last record of your dynaset, records added to base tables may be included if they would be positioned beyond the current record. If you add a record to a dynaset-type Recordset using the AddNew method, however, the record is visible in the Recordset and included in the underlying table where it becomes visible to any new Recordset objects.

The position of the new record depends on the type of Recordset:

In a dynaset-type Recordset object, records are inserted at the end of the recordset, regardless of any sorting or ordering rules that may have been in effect when the recordset was opened.

In a table-type Recordset object whose Index property has been set, records are returned in their proper place in the sort order. If the Index property hasn't been set, new records are returned at the end of the recordset.

The record that was current before you used AddNew remains current. If you want to make the new record current, you can set the Bookmark property to the bookmark identified by the LastModified property setting.


Append Method

Adds a new data access object to a collection.

Syntax

collection.Append object

The Append method syntax has these parts:

Part	Description

collection	Any collection that can accept new objects (for limitations, see the following table).

object	A variable of an object data type identifying the object being appended, which must be of the same type as the elements of collection.

Remarks

Uses of the Append method include adding a new table to a database, adding a field to a table, and adding a field to an index.

The appended object becomes a persistent object, stored on disk, until you delete it using the Delete method. If the collection is a Workspaces collection (which is stored only in memory), the object is active until you remove it using the Close method.

The addition of a new object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

If the object being appended isn't complete (such as when you haven't appended any Field objects to a Fields collection of an Index object before it's appended to an Indexes collection) or if the properties set in one or more subordinate objects are incorrect, the Append method triggers a trappable error. For example, if you haven’t specified a field type and then try to append the Field object to the Fields collection in a TableDef object, the Append method triggers a trappable error.

The following table shows some limitations on the use of the Append method. The object in the first column is an object containing the collection in the second column. The third column indicates when, if ever, you can append an object to that collection (for example, you can never append a Container object to the Containers collection of a Database object).

Object	Collection	When you can use Append
Workspace	Databases	Never; use the OpenDatabase method instead
Database	Containers	Never
Database	Recordsets	Never; use the OpenRecordset method instead
Container	Documents	Never
Index	Fields	When the Index object is a new, unappended object
QueryDef	Fields	Never
QueryDef	Parameters	Never
Recordset	Fields	Never
Relation	Fields	Never
TableDef	Fields	When the Updatable property of the TableDef is set to True
TableDef	Indexes	When the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef	Properties	When the Database, Field, Index, QueryDef, or TableDef is persistent


AppendChunk Method

Appends data from a string expression to a Memo or OLE Object Field object in the Fields collection of a Recordset object.

Syntax

recordset ! field.AppendChunk source

The AppendChunk method syntax has these parts.

Part	Description

recordset	A variable of an object data type that refers to the Recordset object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

source	A string expression or variable containing the data you want to append to the Field object specified by field.

Remarks

You can use the AppendChunk and GetChunk methods to access subsets of data in a Memo and OLE Object field.

You can also use these methods to conserve string space when you work with Memo and OLE Object fields. Certain operations (copying, for example) involve temporary strings. If string space is limited, you may need to work with chunks of a field instead of the entire field.

If there is no current record when you use AppendChunk, an error occurs.

Note   The initial AppendChunk (after the first Edit method), even if the record already contains data, will simply place the data in the field as the only data. Subsequent AppendChunk calls within a single Edit session will then add to the data.


BeginTrans, CommitTrans, Rollback Methods

The transaction methods manage transaction processing during a session defined by a Workspace object as follows:

BeginTrans begins a new transaction.

CommitTrans ends the current transaction and saves the changes.

Rollback ends the current transaction and restores the databases in the Workspace object to the state they were in when the current transaction began.

Syntax

workspace.BeginTrans | CommitTrans | Rollback

The transaction methods have these parts:

Part	Description

workspace	A variable of an object data type identifying the Workspace.

Remarks

You use these methods with a Workspace object when you want to treat a series of changes made to the databases in a session as one unit.

Typically, you use transactions to maintain the integrity of your data when you must update records in two or more tables and make sure changes made are completed (committed) in all tables or none at all (rolled back). For example, if you transfer money from one account to another, you might subtract an amount from one and add the amount to another. If either update fails, the accounts no longer balance. Use the BeginTrans method before updating the first record, and then, if any subsequent update fails, you can use the Rollback method to undo all of the updates. Use the CommitTrans method after you successfully update the last record.

Caution   Within one Workspace object, transactions are always global to the Workspace and aren't limited to only one database or recordset. If you perform operations on more than one database or recordset within a Workspace transaction, the Rollback method restores all operations on those databases and recordsets.

After you use CommitTrans, you can't undo changes made during that transaction unless the transaction is nested within another transaction that is itself rolled back. You can have up to five levels of transactions open at once in a single Workspace object by using multiple, nested combinations of BeginTrans and CommitTrans or Rollback. If you nest transactions, you must save or roll back the current transaction before you can save or roll back a transaction at a higher level of nesting. If you want to have simultaneous transactions with overlapping, non-nested scopes, you can create additional Workspace objects to contain the concurrent transactions.

If you close a Workspace object without saving or rolling back any pending transactions, the transactions are automatically rolled back.

If you use the CommitTrans or Rollback methods without first using the BeginTrans method, an error occurs.

Some databases may not support transactions, in which case the Transactions property of the Database object or Recordset object is False. To make sure that the database supports transactions, check the value of the Transactions property of the Database object before using the BeginTrans method. If you are using a Recordset object based on more than one database, check the Transactions property of the Recordset object. If a recordset is based entirely on Microsoft Jet database engine tables, you can always use transactions. Dynaset-type Recordset objects based on tables created by other database products, however, may not support transactions. For example, you can't use transactions in a Recordset based on a Paradox table. In this case, the Transactions property is False. If the Database or Recordset doesn't support transactions, the methods are ignored and no error occurs.

When using external ODBC SQL databases, you can't nest transactions.

Tip   In addition to performing transactions to maintain data integrity, you can often improve the performance of your application by breaking operations that require disk access on your database into transaction blocks. This ensures buffering of your operations and may greatly reduce the number of times a disk is accessed.

Note   When you begin a transaction, the Jet database engine records its operations in a file kept in the directory specified by the TEMP environment variable on the workstation. If the transaction log file exhausts the available storage on your TEMP drive, the Jet database engine triggers a trappable error (2004). At this point, if you use CommitTrans, an indeterminate number of operations are committed but the remaining uncompleted operations are lost, and the operation has to be restarted. Using a Rollback method releases the transaction log and rolls back all operations in the transaction.


CancelUpdate Method

Cancels any pending updates for the Recordset object represented by the object placeholder.

Syntax

object.CancelUpdate

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The CancelUpdate method cancels any pending updates due to an Edit or AddNew operation. For example, if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was invoked.

Note   Using the CancelUpdate method has the same effect as moving to another record without using the Update method except that the current record doesn't change, and various properties, such as BOF and EOF, aren't updated.

Use the EditMode property to determine if there is a pending operation that can be canceled.


Clone Method

Creates a duplicate Recordset object that refers to the original object.

Syntax

Set duplicate = original.Clone( )

The Clone method syntax has these parts:

Part	Description

duplicate	A variable of an object data type identifying the duplicate Recordset object you're creating.

original	A variable of an object data type identifying the Recordset object you want to duplicate.

Remarks

Use the Clone method to create multiple, duplicate Recordset objects. Each recordset can have its own current record. Using Clone by itself doesn't change the data in the objects or in their underlying structures. Using the Clone method, you can share bookmarks between two or more recordsets because their bookmarks are interchangeable.

Note   When used on a table-type Recordset object, the Index property setting is not cloned on the new copy of the Recordset. You must copy the Index property setting manually.

You can use Clone when you want to perform an operation on a recordset that requires multiple current records. This is faster and more efficient than creating a second recordset.

A recordset you create with Clone initially lacks a current record. To make a record current before you use the recordset object specified by duplicate, you must set the Bookmark property or use one of the Move methods, one of the Find methods (for dynaset- and snapshot-type Recordset objects only), or the Seek method (for table-type Recordset objects only).

Cloning a recordset that resulted from running a QueryDef object doesn't run the query again.

Using the Close method on either the original or duplicate object doesn't affect the other object. For example, using Close on the original Recordset does not close the clone.

Note   You can't use the Clone method with forward-only-scrolling snapshots.


Close Method (DAO)

Closes an open data access object.

Syntax

object.Close

The object placeholder represents the name of an open Database, Recordset, or Workspace object.

Remarks

Closing an open object removes it from the collection to which it's appended. Any attempt to close the default workspace is ignored.

To remove objects from collections other than the Databases, Recordsets, and Workspaces collections, use the Delete method on those collections.

Caution   Use the Update method (if there are pending edits) and the Close method on all open recordset objects before you close a database. If you exit a procedure that declares recordset or Database objects, the database is closed, any unsaved changes are lost, all pending transactions are rolled back, and any pending edits to your data are lost.

If you try to close a Database object while any recordset objects are open, or if you try to close a Workspace object while any Database objects belonging to that specific Workspace are open, those Recordset objects will be closed and any pending updates or edits will be rolled back.

If you try to close a Workspace object while any Database objects belonging to it are open, the operation closes all Database objects belonging to that specific Workspace object which may result in Recordset objects being closed and pending edits lost.

If the Database object is defined outside the scope of the procedure, and you exit the procedure without closing it, the Database object will remain open until explicitly closed or the module in which it is defined is out of scope.

If the Database, Recordset, or Workspace object named by object is already closed when you use Close, a trappable error occurs.

Using the Close method on either the original or duplicate object doesn't affect the other object. For example, using Close on the original Recordset does not close the clone.


CompactDatabase Method

Copies, compacts, and gives you the option of changing the version, collating order, and encryption of a closed database.

Syntax

DBEngine.CompactDatabase olddb, newdb [, locale [, options [, ;pwd=password]]]

The CompactDatabase method syntax has these parts.

Part	Description

olddb	A string expression that identifies an existing, closed database. It can be a full path and filename, such as "C:\MYDB.mdb". If the filename has an extension, you must specify it. If your network supports it, you can also specify a network path, such as "\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb".

newdb	A string expression that is the full path of the compacted database that you're creating. You can also specify a network path as with olddb. You can't use the newdb argument to specify the same database file as olddb.

locale	A string expression used to specify collating order for creating newdb, as specified in Settings. If you omit this argument, the locale of newdb is the same as olddb.

options	An integer that indicates one or more options, as specified in Settings. You can combine options by summing the corresponding constants.

password	An optional string argument containing a password, if the database is password protected.  The string “;pwd=“ must precede the actual password.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property for string comparisons of text.

Constant	Collating order

dbLangGeneral	English, German, French, Portuguese, Italian, and Modern Spanish

dbLangArabic	Arabic

dbLangCzech	Czech

dbLangCyrillic	Russian

dbLangDutch	Dutch

dbLangGreek	Greek

dbLangHebrew	Hebrew

dbLangHungarian	Hungarian

dbLangIcelandic	Icelandic

dbLangNordic	Nordic languages (Microsoft Jet database engine version 1.0 only)

dbLangNorwdan	Norwegian and Danish

dbLangPolish	Polish

dbLangSwedfin	Swedish and Finnish

dbLangSpanish	Traditional Spanish

dbLangTurkish	Turkish

You can use one of the following constants in the options argument to specify whether to encrypt or to decrypt the database as it's compacted.

Constant	Description

dbEncrypt	Encrypt the database while compacting.

dbDecrypt	Decrypt the database while compacting.

If you omit an encryption constant or if you include both dbDecrypt and dbEncrypt, newdb will have the same encryption as olddb.

You can use one of the following constants in the options argument to specify the version of the data format for the compacted database. This constant affects only the version of the data format of newdb and doesn't affect the version of any Microsoft Access-defined objects, such as forms and reports.

Constant	Description

dbVersion10	Creates a database that uses the Microsoft Jet database engine version 1.0 while compacting.

dbVersion11	Creates a database that uses the Jet database engine version 1.1 while compacting.

dbVersion20	Creates a database that uses the Jet database engine version 2.0 while compacting.

dbVersion30	Creates a database that uses the Jet database engine version 3.0 while compacting.

You can specify only one version constant. If you omit a version constant, newdb will have the same version as olddb. You can compact newdb only to a version that is the same or later than that of olddb.

Remarks

As you change data in a database, the database file can become fragmented and use more disk space than necessary. Periodically, you can compact your database to defragment the database file. The compacted database is usually smaller and often runs faster. You can also choose to change the collating order, the encryption, or the version of the data format while you copy and compact the database.

The CompactDatabase method copies all the data and the security permissions settings from the database specified by olddb to the database specified by newdb. In the process, the data in the compacted database is organized contiguously to recover disk space.

You must close olddb before you compact it. In a multiuser environment, other users can't have olddb open while you're compacting it. If olddb isn't closed or isn't available for exclusive use, an error occurs.

Because CompactDatabase creates a copy of the database, you must have enough disk space for both the original and the duplicate databases. The compact operation fails if there isn't enough disk space available. The newdb duplicate database doesn't have to be on the same disk as olddb. After successfully compacting a database, you can delete the olddb file and rename the compacted newdb file to the original filename.

Warning	Because the CompactDatabase method will not convert Microsoft Access objects, using CompactDatabase to convert a database containing such objects is not recommended.  To convert a database containing Microsoft Access objects, click Tools Convert on the Microsoft Access menubar.


CopyQueryDef Method

Returns a QueryDef object which is a copy of the QueryDef used to create the Recordset object represented by the object placeholder.

Syntax

Set <querydefobject> = <object>.CopyQueryDef

The <querydefobject> is an object variable declared as a QueryDef.

Remarks

You must first open a Recordset with the OpenRecordset method before using the CopyQueryDef method. CopyQueryDef creates a new QueryDef that is a duplicate of the QueryDef used to create the Recordset.  If a QueryDef wasn't used to create this Recordset, you’ll see a message that the feature is not available.


CreateDatabase Method

Creates a new Database object, saves the database on disk and returns an opened Database object.

Syntax

Set database = workspace.CreateDatabase (databasename, locale [, options])

The CreateDatabase method syntax has these parts.

Part	Description

database	A variable of an object data type that references the Database object you're creating.

workspace	A variable of an object data type that represents the existing Workspace object that will contain the database. If you omit the workspace part, the default Workspace is used.

databasename	A string expression that is the name of the database file that you're creating. It can be the full path and filename, such as "C:\MYDB.mdb". If you don't supply a filename extension, .mdb is appended. If your network supports it, you can also specify a network path, such as  "\\MYSERVER\MYSHARE\MYDIR\MYDB". Only .mdb database files can be created using this method.

locale	A string expression used to specify collating order for creating the database. You must supply this argument or an error will occur. See the table that lists locale constants later in this topic.

options	An integer that indicates one or more options, as specified in Settings. You can combine options by summing the corresponding constants.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property of text for string comparisons.

Constant	Collating order

dbLangGeneral	English, German, French, Portuguese, Italian, and Modern Spanish

dbLangArabic	Arabic

dbLangCzech	Czech

dbLangCyrillic	Russian

dbLangDutch	Dutch

dbLangGreek	Greek

dbLangHebrew	Hebrew

dbLangHungarian	Hungarian

dbLangIcelandic	Icelandic

dbLangNordic	Nordic languages (Microsoft Jet database engine version 1.0 only)

dbLangNorwdan	Norwegian and Danish

dbLangPolish	Polish

dbLangSwedfin	Swedish and Finnish

dbLangSpanish	Traditional Spanish

dbLangTurkish	Turkish

You can use one or more of the following constants in the options argument to specify which version the data format should have and whether or not to encrypt the database.

Constant	Description

dbEncrypt	Creates an encrypted database.

dbVersion10	Creates a database that uses the Jet database engine version 1.0.

dbVersion11	Creates a database that uses the Jet database engine version 1.1.

dbVersion20	Creates a database that uses the Jet database engine version 2.0.

dbVersion30	Creates a database that uses the Jet database engine version 3.0.

If you omit the encryption constant, an unencrypted database is created. You can specify only one version constant. If you omit a version constant, a database that uses the Jet database engine version 3.0 is created.

Remarks

The CreateDatabase method creates and opens a new, empty database and returns the Database object. You must complete its structure and content using additional data access objects. If you want to make a partial or complete copy of an existing database, you can use the CompactDatabase method to make a copy that you can customize.


CreateField Method

Creates a new Field object.

Syntax

Set variable = object.CreateField([name[, type [, size]]])

The CreateField method syntax has these parts:

Part	Description

variable	A variable declared as an object data type Field.

object	The variable name of the Index, Relation, or TableDef object you want to use to create the new Field object.

name	A String variable that uniquely names the new Field object. See the Name property for details on valid Field names.

type	An Integer constant that determines the data type of the new Field object. See the Type property for valid data types.

size	An integer that indicates the maximum size, in bytes, of a Field object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Remarks

If you omit one or more of the optional parts when you use CreateField, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the new object, you can alter some but not all of its property settings. See the individual property topics for more details.

Note   The type and size arguments apply only to Field objects in a TableDef object. These arguments are ignored when a Field object is associated with Index and Relation objects.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Field object from a collection, use the Delete method on the collection. You can't delete a Field object from a TableDef object's Fields collection once an index has been created that references the field.


CreateGroup Method

Creates a new Group object.

Syntax

Set variable = object.CreateGroup([name[, pid]])

The CreateGroup method syntax has these parts.

Part	Description

variable	A variable declared as object data type Group.

object	The variable name of the User or Workspace object you want to use to create the new Group object.

name	A String variable that uniquely names the new Group object. See the Name property for details on valid Group names.

pid	A String variable containing the PID of a group account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

Remarks

If you omit one or both of the optional parts when you use CreateGroup, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Group object from a collection, use the Delete method on the collection.


CreateIndex Method

Creates a new Index object.

Syntax

Set variable = tabledef.CreateIndex([name])

The CreateIndex method syntax has these parts:

Part	Description

variable	A variable declared as object data type Index.

tabledef	The variable name of the TableDef object you want to use to create the new Index object.

name	A String variable that uniquely names the new Index object. See the Name property for details on valid Index names.

Remarks

If you omit the optional name part when you use CreateIndex, you can use an appropriate assignment statement to set or reset the Name property before you append the new object to a collection. After you append the object, you may or may not be able to set its Name property, depending on the type of object the Indexes collection resides in. See the Name property topic for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove an Index object from a collection, use the Delete method on the collection.


CreateProperty Method

Creates a new user-defined Property object.

Syntax

Set variable = object.CreateProperty([name[, type[, value[, fDDL]]]])

The CreateProperty method syntax has these parts:

Part	Description

variable	A variable declared as an object data type Property.

object	The variable name of the Database, Field, Index, QueryDef, or TableDef object you want to use to create the new Property object.

name	A String variable that uniquely names the new Property object. See the Name property for details on valid Property names.

type	An Integer constant that defines the data type of the new Property object. See the Type property for valid data types.

value	A Variant variable containing the initial property value. See the Value property for details.

fDDL	A Boolean variable indicating whether or not the Property is a DDL object. The default is False. If the fDDL is True, this Property object can't be changed or deleted unless the user has dbSecWriteDef permission.

Remarks

You can create a user-defined Property object only in the Properties collection of an object that is persistent (that is, already stored on disk).

If you omit one or more of the optional parts when you use CreateProperty, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a user-defined Property object from the collection, use the Delete method on the Properties collection. You can't delete built-in properties.

Note    If you omit the fDDL part, it defaults to False (non-DDL). Because no corresponding DDL property is exposed, you must delete and re-create a Property object you want to change from DDL to non-DDL,


CreateQueryDef Method

Creates a new QueryDef object in a specified database.

Syntax

Set querydef = database.CreateQueryDef([name][, sqltext])

The CreateQueryDef method syntax has these parts.

Part	Description

querydef	A variable of an object data type that references the QueryDef object you want to create.

database	A variable of an object data type that references the open Database object that contains the new QueryDef.

name	A string expression identifying the new QueryDef.

sqltext	A string expression (a valid SQL statement) that defines the QueryDef. If you omit this argument, you can define the QueryDef by setting its SQL property before or after you append it to a collection.

Remarks

If you include name but omit sqltext or include both name and sqltext, the QueryDef is automatically saved when you create or change it.

If the object specified by name is already a member of the QueryDefs collection, a trappable error occurs.

You can create a temporary QueryDef by setting the Name property of a newly created QueryDef to a zero-length string ("") or by using a zero-length string for the name argument when you execute the CreateQueryDef method. You can't append a temporary QueryDef to any collection because a zero-length string isn't a valid name for a permanent QueryDef. You can set the Name and SQL properties of the newly created QueryDef and subsequently append the QueryDef to the QueryDefs collection where it's stored in the database. If you provide anything other than a zero-length string for the name when you create a QueryDef, the resulting QueryDef object is automatically appended to the QueryDefs collection.

To remove a QueryDef object from a QueryDefs collection, use the Delete method on the collection.

To run the SQL statement in a QueryDef object, use the Execute method.

Using a QueryDef object is the preferred way to perform SQL pass-through queries with ODBC databases. See the QueryDef object for more information.


CreateRelation Method

Creates a new Relation object.

Syntax

Set variable = database.CreateRelation([name[, table[, foreigntable[, attributes]]]])

The CreateRelation method syntax uses these parts.

Part	Description

variable	A variable declared as an object data type Relation.

database	The variable name of the Database object you want to use to create the new Relation object.

name	A String variable that uniquely names the new Relation object. See the Name property for details on valid Relation names.

table	A String variable that names the primary table in the relation. If the table doesn't exist before you append the Relation object, a trappable error occurs.

foreigntable	A String variable that names the foreign table in the relation. If the table doesn't exist before you append the Relation object, a trappable error occurs.

attributes	A Long variable that contains information about the relationship type. See the Attributes property for details.

Remarks

The Relation object relays information to the Microsoft Jet database engine about the relationship between fields in two TableDef or QueryDef objects. The Jet database engine can provide referential integrity through the Attributes property.

If you omit one or more of the optional parts when you use CreateRelation, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, none of its property settings can be altered. See the individual property topics for more details.

Before you can use the Append method on a Relation object, you must append the appropriate Field objects to define the primary and foreign key relationship tables.

If name refers to an object that is already a member of the collection or if the Field object names provided in the subordinate Fields collection are invalid, a trappable error occurs when you use the Append method.

To remove a Relation object from a collection, use the Delete method on the collection.


CreateTableDef Method

Creates a new TableDef object.

Syntax

Set variable = database.CreateTableDef([name[, attributes[, source[, connect]]]])

The CreateTableDef method syntax has these parts:

Part	Description

variable	A variable declared as an object data type TableDef.

database	The variable name of the Database object you want to use to create the new TableDef object.

name	A String variable that uniquely names the new TableDef object. See the Name property for details on valid TableDef names.

attributes	A Long variable that indicates one or more characteristics of the new TableDef object. See the Attributes property for more information.

source	A String variable containing the name of a table in an external database that is the original source of the data. The source string becomes the SourceTableName property setting of the new TableDef object.

connect	A String variable containing information about the source of an open database, a database used in a pass-through query, or an attached table. See the Connect property for more information on valid connection strings.

Remarks

If you omit one or more of the optional parts when you use CreateTableDef, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its properties. See the individual property topics for more details.

If name refers to an object that is already a member of the collection or you specify an invalid property in the TableDef or Field object you're appending, a trappable error occurs when you use the Append method.

To remove a TableDef object from a collection, use the Delete method on the collection.


CreateUser Method

Creates a new User object.

Syntax

Set variable = object.CreateUser([name[, pid [, password]]])

The CreateUser method syntax has these parts:

Part	Description

variable	A variable declared as an object data type User.

object	The variable name of the Group or Workspace object you want to use to create the new User object.

name	A String variable that uniquely names the new User object. See the Name property for details on valid User names.

pid	A String variable containing the PID of a user account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

password	A String variable containing the password for the new User object. The password can be up to 14 characters long and can include any characters except the ASCII character 0 (null). See the Password property for more information on valid passwords.

Remarks

If you omit one or more of the optional parts when you use CreateUser, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a User object from a collection, use the Delete method on the collection.


CreateWorkspace Method

Creates a new Workspace object.

Syntax

Set variable = CreateWorkspace(name, user, password)

The CreateWorkspace method syntax has these parts:

Part	Description

variable	A variable declared as object data type Workspace.

name	A String variable that uniquely names the new Workspace object. See the Name property for details on valid Workspace names.

user	A String variable that identifies the owner of the new Workspace object. See the UserName property for more information.

password	A String variable containing the password for the new Workspace object. The password can be up to 14 characters long and can include any characters except ASCII character 0 (null). See the Password property for more information on valid passwords.

Remarks

Unlike the other methods you use to create data access objects, CreateWorkspace requires that you provide all of its parts. In addition, Workspace objects aren't permanent and can't be saved. Once you create a Workspace object, you can't alter any of its property settings.

You don't have to append the new Workspace object to a collection before you can use it. You append a newly created Workspace object only if you need to be able to refer to it through the Workspaces collection.

If name refers to an object that is already a member of the Workspaces collection, a trappable error occurs.

Once you use CreateWorkspace to create a new Workspace object, a Workspace session is started, and you can refer to the Workspace object in your application.

To remove a Workspace object from the Workspaces collection, close all open databases and then use the Close method on the Workspace object.


Delete Method (DAO)

Recordset objects [image] deletes the current record in an open dynaset-type or table-type Recordset object.

Collections [image] deletes a stored object from a collection.

Syntax

recordset.Delete

collection.Delete objectname

The Delete method syntax has these parts:

Part	Description

recordset	A variable of an object data type identifying an open dynaset-type or table-type Recordset object containing the record you want to delete.

collection	A variable of an object data type identifying a collection.

objectname	A String that is the Name property setting of an object in collection.

Remarks

You can use the Delete method to delete a current record from a recordset or a member from a collection, such as a stored table from a database, a stored field from a table, and a stored index from a table.

Recordsets:  When you delete records from a recordset, there recordset must contain a current record before you use Delete; otherwise, a trappable error occurs.

In table- and dynaset-type Recordset objects, Delete removes the current record and makes it inaccessible. Although you can't edit or use the deleted record, it remains current. Once you move to another record, however, you can't make the deleted record current again. Subsequent references to a deleted record in a Recordset are invalid and produce an error.

You can undelete a record if you use transactions and the Rollback method.

If the base table is the primary table in a cascade delete relationship, deleting the current record may also delete one or more records in a foreign table.

Collections:  You can use the Delete method to delete a persistent object. However, if the collection is a Databases, Recordsets, or Workspaces collection (each of which is stored only in memory), you can remove an open or active object only by closing that object using the Close method.

The deletion of a stored object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

When you delete a TableDef object from the TableDefs collection, you delete the table definition and the data in the table.

The following table shows some limitations on the use of the Delete method. The object in the first column contains the collection in the second column. The third column indicates when, if ever, you can delete an object from that collection (for example, you can never delete a Container object from the Containers collection of a Database object).

Object	Collection	When you can use Delete method
DBEngine	Workspaces	Never; use the Close method instead
Workspace	Databases	Never; use the Close method instead
Database	Containers	Never
Database	Recordsets	Never; use the Close method instead
Container	Documents	Never
Index	Fields	On new objects that haven't been appended to the database
QueryDef	Fields	Never
QueryDef	Parameters	Never
Recordset	Fields	Never
Relation	Fields	On new objects that haven't been appended to the database
TableDef	Fields	On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
TableDef	Indexes	On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef	Properties	When the property is user-defined


Edit Method

Copies the current record from a dynaset-type or table-type Recordset object to the copy buffer for subsequent editing.

Syntax

recordset.Edit

The recordset placeholder represents the name of an open, updatable Recordset object that contains the record you want to edit.

Remarks

Once you use the Edit method, changes made to the current record's fields are copied to the copy buffer. After you make the desired changes to the record, use the Update method to save your changes.

Caution    If you edit a record and then perform any operation that moves to another record without first using Update, your changes are lost without warning. In addition, if you close recordset or end the procedure which declares the recordset or the parent Database object, your edited record is discarded without warning.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the updating is complete. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it's updated in the database. If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197).

Note   Optimistic locking is always used on external database formats, such as ODBC and installable ISAM.

The current record remains current after you use Edit.

To use Edit, there must be a current record. If there is no current record or if recordset doesn't refer to an open table-type or dynaset-type Recordset object, an error occurs.

Using Edit produces an error under the following conditions:

There is no current record.

The database or recordset is read-only.

No fields in the record are updatable.

The database or recordset was opened for exclusive use by another user.

Another user has locked the page containing your record.


Execute Method

Runs an action query or executes an SQL statement on a specified Database object.

Syntax

database.Execute source[, options]

querydef.Execute [options]

For a Database object, the Execute method syntax has these parts.

Part	Description

database	The name of the Database object on which the query will run.

source	The SQL statement or QueryDef object.

options	An integer constant that determines the data integrity characteristics of the query, as specified in Settings.

For a QueryDef object, the Execute method syntax has these parts.

Part	Description

querydef	The name of the QueryDef object whose SQL property setting specifies the SQL statement to execute.

options	An integer constant that determines the data integrity characteristics of the query, as specified in Settings.

Settings

You can use the following constants for the options part.

Constant	Description

dbDenyWrite	Deny write permission to other users.

dbInconsistent	(Default) Inconsistent updates.

dbConsistent	Consistent updates.

dbSQLPassThrough	SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.

dbFailOnError	Rolls back updates if an error occurs.

dbSeeChanges	Generates a run-time error if another user is changing data you are editing.

Remarks

The Execute method is valid only for action queries. If you use Execute with another type of query, an error occurs. Because an action query doesn't return any records, Execute doesn't return a recordset.

Tips

Given a syntactically correct SQL statement and proper permissions, the Execute method won't fail [image] even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query. This option generates a trappable error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted.

For best performance, especially in a multiuser environment, nest the Execute method inside a transaction:  Use the BeginTrans method on the current Workspace object, then use the Execute method, and complete the transaction by using the CommitTrans method on the Workspace. This saves changes on disk and frees any locks placed while the query was running.

Use the RecordsAffected property of the Database or Querydef object to determine the number of records affected by the most recent Execute method. For example, RecordsAffected contains the number of records deleted, updated, or inserted when executing an action query. When you use the Execute method to run a Querydef, the RecordsAffected property of the Querydef object is set to the number of records affected.

If both dbInconsistent and dbConsistent are included or if neither is included, the result is the default.

Using Execute on a query that selects records produces an error.

Execute doesn't return a recordset.


FieldSize Method (DAO)

Returns the number of bytes used in the database (rather than in memory) of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.

Syntax

varname = recordset ! field.FieldSize( )

The FieldSize method syntax has these parts.

Part	Description

varname	The name of a Long or Variant variable.

recordset	A variable of an object data type that specifies the Recordset object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

Remarks

Because the size of an OLE Object field or Memo field can exceed 64K, you should assign the value returned by FieldSize to a variable large enough to store a Long variable.

You can use FieldSize with the AppendChunk and GetChunk methods to manipulate large fields.

Note   To determine the size of a Field object (except Memo and Long Binary types), use the Size property.


FillCache Method

Fills all or a part of a local cache for a Recordset object that contains data from an ODBC data source.

Syntax

recordset.FillCache [rows[, start]]

The FillCache method syntax has these parts.

Part	Description

recordset	A Recordset object created from an ODBC data source, such as a TableDef representing an attached table or a QueryDef object derived from such a TableDef.

rows	An Integer specifying the number of rows to fill in the cache. If you omit this argument, the value is determined by the CacheSize property setting.

start	A string specifying a bookmark. The cache is filled starting from the record indicated by this bookmark. If you omit this argument, the cache is filled starting from the record indicated by the CacheStart property.

Remarks

Caching improves the performance of an application that retrieves, or fetches, data from a remote server. A cache is space in local memory that holds the data most recently fetched from the server on the assumption that the data will probably be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the data first rather than fetching it from the server, which takes more time. Data that doesn't come from an ODBC data source isn't saved in the cache.

Rather than waiting for the cache to be filled with records as they are fetched, you can explicitly fill the cache at any time using the FillCache method. This is a faster way to fill the cache because FillCache fetches several records at once instead of one at a time. For example, while each screenful of records is being displayed, you can have your application use FillCache to fetch the next screenful of records.

Any ODBC database accessed with Recordset objects can have a local cache. To create the cache, open a Recordset object from the remote data source, and then set the CacheSize and CacheStart properties of the Recordset.

If rows and start create a range of records that is partly or wholly outside the range of records specified by the CacheSize and CacheStart properties, the portion of the recordset outside this range is ignored and isn't loaded into the cache.

If FillCache requests more records than remain in the remote data source, only the remaining records are fetched, and no error occurs.

Notes

 	Records fetched from the cache don't reflect changes made concurrently to the source data by other users.

FillCache fetches only records not already cached. To force an update of all the cached data, set the CacheSize property of the Recordset to 0, set it to the size of the cache you originally requested, and then use FillCache.


FindFirst, FindLast, FindNext, FindPrevious Methods

Locates the first, last, next, or previous record in a dynaset- or snapshot-type Recordset object that satisfies the specified criteria and makes that record the current record.

Syntax

recordset.{FindFirst | FindLast | FindNext | FindPrevious} criteria

The Find methods have these parts.

Part	Description

recordset	The name of an existing dynaset- or snapshot-type Recordset object.

criteria	A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

If you want to include all the records in your search [image] not just those that meet a specific condition [image] use the Move methods to move from record to record. To locate a record in a table-type Recordset, use the Seek method.

If a record matching the criteria isn't located, the current record pointer is undetermined, and the NoMatch property is set to True. If recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution    If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without updating, your changes are lost without warning.

Each of the Find methods begins its search from the location and in the direction specified in the following table.

Find methods	Begin	Search direction
FindFirst	Beginning of recordset	End of recordset
FindLast	End of recordset	Beginning of recordset
FindNext	Current record	End of recordset
FindPrevious	Current record	Beginning of recordset
When you use the FindLast method, the Microsoft Jet database engine fully populates your recordset before beginning the search, if this hasn't already been done.

Using one of the Find methods isn't the same as using a Move method, however, which simply makes the first, last, next or previous record current without specifying a condition. You can follow a Find operation with a Move operation.

Always check the value of the NoMatch property to determine whether the Find operation has succeeded. If the search succeeds, NoMatch is set to False. If it fails, NoMatch is set to True and the current record isn't defined. In this case, you must position the current record pointer back to a valid record, as shown in the following example.

Dim Here as Variant

Here = rstCustomers.Bookmark

rstCustomers.Find "Name = 'Ms. Schmidt'"	' Search for a name in the
' recordset.

If rstCustomers.NoMatch then 	' Was it found?

rstCustomers.Bookmark = Here	' If not, go back to
' previously current record.

Else

. 	' Match found.

...

...

End If

Using the Find methods with ODBC-accessed recordsets can be inefficient. You may find that rephrasing your criteria to locate a specific record is faster, especially when working with large recordsets.

You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you're not using the U.S. version of the Jet database engine; otherwise, the data may not be found. Use the Visual Basic Format function to convert the date. For example:

rstEmployees.FindFirst "HireDate > #" & Format(mydate, 'm/d/yy' ) & "#"

When working with ODBC databases and large dynasets, you might discover that using the Find methods or using the Sort or Filter properties is slow. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or QueryDef objects that retrieve specific indexed records.

Note   You can't use the Find methods with forward-only-scrolling snapshots.


GetChunk Method

Returns all or a portion of the contents of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.

Syntax

stringvar = recordset ! field.GetChunk(offset, numbytes)

The GetChunk method syntax has these parts:

Part	Description

stringvar	The name of a String variable or Variant that receives the data from the Field object named by field.

recordset	A variable of an object data type that specifies the Recordset object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo) or dbLongBinary (OLE Object).

offset	A numeric expression that is the number of bytes to skip before copying begins.

numbytes	A numeric expression that is the number of bytes you want to return.

Remarks

Assign the bytes returned by GetChunk to stringvar. Use GetChunk to return a portion of the total data value at a time. You can use the AppendChunk method to reassemble the pieces.

If offset is 0, GetChunk begins copying from the first byte of the field.

If numbytes is greater than the number of bytes in the field, the actual number of bytes in the field is returned.

Note

Use a Memo-type field for human-readable textual data, and put binary data only in OLE type fields. Doing otherwise will cause undesirable results. For more information, see Choosing a Field Data Type.


GetRows Method

Retrieves multiple rows of a Recordset into an array.

Syntax

varArray = object.GetRows (numrows)

The GetRows Method syntax has the following parts.

Part	Description

varArray	The name of a Variant type variable to store the returned data.

object 	An object expression that evaluates to an object in the Applies To list.

numrows	The number of rows to retrieve.

Remarks

Use the GetRows method to copy one or more entire records from a Recordset. GetRows returns a two-dimensional array. The first subscript identifies the field and the second identifies the row number, as follows:

avarRecords(intField, intRecord)

To get the first field value in the second row returned, use the following:

field1 = avarRecords(0,1)

To get the second field value in the first row, use the following:

field2 = avarRecords(1,0)

If more rows are requested than are available, then only the number available are returned. Use Ubound to determine how many rows were actually fetched, as the array is sized to fit how many rows were returned. For example, if you returned the results into a variant called varA, you could determine how many rows were actually returned by using:

numReturned = Ubound(varA,2) + 1

The "+ 1" is used because the first data returned is in the 0 element of the array. The number of rows that can be fetched is constrained by available memory and should be chosen to suit your application—don't expect to use GetRows to bring your whole table into an array if it is a large table.

Because all fields of the recordset are returned in the array, including long memo and binary fields, you might want to use a query that restricts the columns returned.

After a call to GetRows, the current record is positioned at the next unread row. That is, GetRows has an equivalent positioning effect to Move numrows.

If you are trying to fetch all the rows using multiple GetRows calls, use the EOF property to be sure that you're at the end of the Recordset. GetRows returns less than the number requested either at the end of the Recordset, or if it cannot fetch a row in the range requested. For example, if a fifth record cannot be retrieved in a group of ten records that you're trying to fetch, GetRows returns four records and leaves currency on the record that caused a problem. It will not generate a run-time error. This situation might occur if a record in a dynaset has been deleted by another user.


Idle Method

Suspends data processing, enabling the Microsoft Jet database engine to complete any pending tasks such as memory optimization or page timeouts.

Syntax

DBEngine.Idle [dbFreeLocks]

Remarks

You use the Idle method to provide the Jet database engine with the opportunity to perform background tasks that may not be up-to-date because of intense data processing. This is often true in multiuser, multitasking environments in which there isn't enough background processing time to keep all records in a recordset current.

Usually, read locks are removed and data in local dynaset-type Recordset objects is updated only when no other actions (including mouse movements) are occurring. If you periodically use the Idle method, you provide the database engine with time to catch up on background processing tasks by releasing unneeded read locks. If you specify the dbFreeLocks constant as an argument, processing is delayed until all read locks are released.

This method isn't needed in single-user environments unless multiple instances of an application are running. The Idle method may increase performance in a multiuser environment because it forces the database engine to flush data to disk, releasing locks on memory.

You can also release read locks by making operations part of a transaction. For example:

wspSession.BeginTrans

Set rstEmployees = rstEmployees.OpenRecordset("Employees")

wspSession.CommitTrans

Do Until rstEmployees.EOF

...

...

...

rstEmployees.MoveNext

Loop


MakeReplica Method

Makes a new replica based on the current replicable database using the supplied filename.

Syntax

database.MakeReplica replica, description [, dbRepMakeReadOnly]

The MakeReplica Method syntax has the following parts.

Part	Description

database	An existing, replicable Database object variable.

replica	The path and file name to be given the new replica. If replica is an existing filename, then the method fails and returns an error message.

description	Text string describing the replica to be created.

If dbRepMakeReadOnly is supplied, then the replicable elements of the newly created database will not be modifiable.

Remarks

As with most of the replication methods and properties, the database has to be a replicable database for this method to work.

Note   The MakeReplica method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Move Method

Moves the position of the current record in a Recordset object.

Syntax

recordset.Move rows[, start]

The Move method syntax has these parts.

Part	Description

recordset	The name of the Recordset object whose current record position is being moved.

rows	A signed Long value specifying the number of rows the position will move. If rows is greater than 0, the position is moved forward (toward the end of the file). If rows is less than 0, the position is moved backward (toward the beginning of the file).

start	A String value identifying a bookmark. If start is specified, the move begins relative to this bookmark. If start is not specified, Move begins from the current record.

Remarks

If using Move would move the position of the current record to a position before the first record, the position is moved to the beginning-of-file (BOF) position. If the Recordset contains no records and its BOF property is set to True, using this method to move backward produces a trappable run-time error. If either the BOF or EOF property is True and you attempt to use the Move method without a valid bookmark, a trappable error is triggered.

If using Move would move the position of the current record to a position after the last record, the position is moved to the end-of-file (EOF) position. If the Recordset is based on a query, then this approach forces the query to be run on the specified number of rows. If the Recordset contains no records and its EOF property is set to True, then using this method to move forward produces a trappable run-time error.

Notes

When you use Move on a forward-only scrolling snapshot, the rows argument must be a positive integer and bookmarks aren't allowed. This means you can only move forward.

To make the first, last, next, or previous record in a Recordset the current record, use the MoveFirst, MoveLast, MoveNext, or MovePrevious method.


MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Move to the first, last, next, or previous record in a specified Recordset object and make that record the current record.

Syntax

object.{MoveFirst | MoveLast | MoveNext | MovePrevious}

The object placeholder represents an object expression that evaluates to the name of an open Recordset object.

Remarks

Use the Move methods to move from record to record without applying a condition. Use the Find methods to locate records in a dynaset- or snapshot-type Recordset object that satisfy a certain condition. To locate a record in a table-type Recordset object, use the Seek method.

Caution   If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without updating, your changes are lost without warning.

When you open the recordset named by recordset, the first record is current and the BOF property is set to False. If the recordset contains no records, the BOF property is set to True, and there is no current record.

If the first or last record is already current when you use MoveFirst or MoveLast, the current record doesn't change.

If you use MovePrevious when the first record is current, the BOF property is set to True, and there is no current record. If you use MovePrevious again, an error occurs; BOF remains True.

If you use MoveNext when the last record is current, the EOF property is set to True, and there is no current record. If you use MoveNext again, an error occurs; EOF remains True.

If recordset refers to a table-type Recordset, movement follows the current index. You can set the current index using the Index property. If you don't set the current index, the order of returned records is undefined.

If you use MoveLast on a Recordset object based on an SQL query or QueryDef, the query is forced to completion and the Recordset object is fully populated.

Notes

You can't use the MoveFirst, MoveLast, or MovePrevious methods with a forward-only scrolling snapshot.

To move the position of the current record in a Recordset object a specific number of records forward or backward, use the Move method.


NewPassword Method

Changes the password of an existing user account or Jet version 3.0 database.

Syntax

object.NewPassword oldpassword, newpassword

The NewPassword method syntax has these parts.

Part	Description

object	A variable of an object data type that represents the User object or a Jet 3.0 Database object whose Password property you want to change.

oldpassword	A string expression that is the current setting of the Password property of the User or Jet 3.0 Database object.

newpassword	A string expression that is the new setting of the Password property of the User or Jet 3.0 Database object.

Remarks

The oldpassword and newpassword strings can be up to 14 characters long and can include any characters except the ASCII character 0 (null). To clear the password, use a zero-length string ("") for newpassword.

Passwords are case-sensitive.

If object refers to a User object that is not an element of a Users collection, an error occurs. To set a new password, you must either be logged on as the user whose user account you're changing, or you must be a member of the Admins group. The Password property of a User object is write-only [image] users can't read the current value.

If object refers to a Jet version 3.0 Database object, this method offers a limited form of security in the form of password protection. When creating or opening a version 3.0 .mdb file, part of the Connect string describes the password; thus, no work is required of your DAO code.

If a database has no password, one will be created automatically by passing “” for the old password. If you lose your password, you can never open the database again.


OpenDatabase Method

Opens a specified database in a session and returns a reference to the Database object that represents it. The open database is automatically added to the Databases collection.

Syntax

Set database = [workspace.]OpenDatabase(dbname[, exclusive[, read-only[, source]]])

The OpenDatabase method syntax has these parts.

Part	Description

database	A variable of a Database object data type that references the Database object that you're opening.

workspace	A variable of a Workspace object data type that references the existing Workspace object that will contain the database.

dbname	A string expression that is the name of an existing database file.

Some considerations apply when using dbname:

  If it refers to a database that is already open for exclusive access by another user, an error occurs.

  If it doesn't refer to an existing database or valid ODBC data source name, an error occurs. (See Remarks for more information on opening ODBC databases.)

  If it's a zero-length string ("") and source is "ODBC;", a dialog box listing all registered ODBC data source names is displayed so the user can select a database. (See Remarks for more information on opening ODBC databases.)

exclusive	A Boolean expression that is True if the database is to be opened for exclusive (nonshared) access and False if the database is to be opened for shared access. If you omit this argument, the database is opened for shared access.

read-only	A Boolean value that is True if the database is to be opened for read-only access and False if the database is to be opened for read/write access. If you omit this argument, the database is opened for read/write access.

source	A string expression used for opening the database, including databases with passwords. Note that the NewPassword method, when used on a Database object, changes the password parameter that appears in the “PWD=...” part of this argument. You must supply the exclusive and read-only arguments to supply a source string. See the Connect property for syntax, and see Remarks for more information on opening ODBC databases.

Remarks

To close a database, and thus remove its Database object from the Databases collection, use the Close method on the object.

Because attached tables on ODBC databases improve performance, it’s preferable to use them rather than opening ODBC databases directly. To open an ODBC database directly, you must specify a registered ODBC data source name. If the filename has an extension, it's required. If your network supports it, you can also specify a network path, such as

"\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb".

For more information about ODBC drivers, such as SQL Server, see the Help file provided with the driver.

Note   The source argument is expressed in two parts: the database type, followed by a semicolon (;) and the optional arguments. The database type, such as "ODBC;" or "FoxPro 2.5" must be provided first. The optional arguments follow in no particular order, separated by semicolons. One of the parameters may be the password (if one is assigned). For example, .source = ("FoxPro 2.5; pwd=mypassword"). See the source argument, defined earlier in this topic, for more information.


OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

Set variable = database.OpenRecordset(source[, type[, options]])

Set variable = object.OpenRecordset([type[, options]])

The OpenRecordset method syntax has these parts.

Part	Description

variable	A variable that has been declared as an object data type Recordset.

database	The name of an existing Database object you want to use to create the new Recordset.

object	The name of an existing QueryDef, Recordset, or TableDef object you want to use to create the new Recordset. This argument can't be the name of a forward-only scrolling snapshot.
If object refers to a dynaset or snapshot-type Recordset object, the type of the new object is the same as that of the Recordset specified by object. If object refers to a table-type Recordset object, the type of the new object is a dynaset-type 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, the source can only be a table name.

type	If you don't specify a type, OpenRecordset creates a table-type Recordset if possible. If you specify an attached table or query, OpenRecordset creates a dynaset-type Recordset. This value can be one of the following Integer constants:

  dbOpenTable [image] to open a table-type Recordset object.

  dbOpenDynaset [image] to open a dynaset-type Recordset object.

  dbOpenSnapshot [image] to open a snapshot-type Recordset object.

options	Any combination (or none) of the following Integer constants specifying characteristics of the new Recordset, such as restrictions on other users' ability to edit and view it:

  dbAppendOnly [image] You can append only new records (dynaset-type Recordset only).

  dbForwardOnly [image] The Recordset is a forward-only scrolling snapshot. Note that Recordset objects created with this option cannot be cloned and only support the MoveNext method to move through the records.

 dbSQLPassThrough [image] SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.

  dbSeeChanges [image] Generate a run-time error if another user is changing data you are editing.

  dbDenyWrite [image] Other users can't modify or add records.

  dbDenyRead [image] Other users can't view records (table-type Recordset only).

  dbReadOnly [image] You can only view records; other users can modify them.

  dbInconsistent [image] Inconsistent updates are allowed (dynaset-type Recordset only).

  dbConsistent [image] Only consistent updates are allowed (dynaset-type Recordset only).

Note   The constants dbConsistent and dbInconsistent are mutually exclusive. You can use one or the other, but not both in a given instance of OpenRecordset.

Remarks

If object refers to a QueryDef, or a dynaset- or snapshot-type Recordset, or if source refers to an SQL statement or a TableDef that represents an attached table, you can't use dbOpenTable for the type argument; if you do, a trappable error occurs.

If you want to use an SQL pass-through query on an attached table, you must first set the Connect property of the attached table's database to a valid ODBC connect string. For more information on this, search for Connect in the Help menu.

Use the dbSeeChanges flag if you want to trap changes made by another user or another program on your machine when you're editing or deleting the same record. For example, if two users start editing the same record, the first user to execute the Update method succeeds. When the Update method is executed by the second user, a run-time error occurs. Similarly, if the second user tries to use the Delete method to delete the record, and it has already been changed by the first user, a run-time error also occurs.

Typically, if the user gets this error while updating, your code should refresh the contents of the fields and retrieve the newly modified values. If the error occurs in the process of deleting, your code could display the new record data to the user and a message indicating that the data has recently changed. At this point, your code can request a confirmation that the user still wants to delete the record.

Tip   Use the forward-only scrolling option (dbForwardOnly) to improve performance when your application makes a single pass through a Recordset opened from an ODBC data source.

When you close a Recordset using the Close method, it's automatically deleted from the Recordsets collection.


Refresh Method

Updates the objects in a collection to reflect the current database’s schema.

Syntax

collection.Refresh

Remarks

The Refresh method can't be used with collections that aren't persistent, such as Databases, Recordsets, or Workspaces.

Note   To determine the position that the Microsoft Jet database engine uses for Field objects in the Fields collection of a QueryDef, Recordset, or TableDef object, use the OrdinalPosition property of each Field object. The Refresh method may change the order of objects within the Fields collection, if the OrdinalPosition property of a Field object in the collection has been changed.

Use the Refresh method in multiuser environments in which other users may change the database. You may also need to use it on any collections that are indirectly affected by changes to the database. For example, if you change a Users collection, you may need to refresh a Groups collection before using the Groups collection.

Tip   A collection is filled with objects the first time it's referred to and won't automatically reflect subsequent changes made to it by other users. If it's likely that a collection has been changed by another user, use the Refresh method on the collection immediately before carrying out any task in your application that assumes the presence or absence of a particular object in the collection. This will ensure that the collection is as up-to-date as possible.


RefreshLink Method

Updates the connection information for an attached table.

Syntax

tabledef.RefreshLink

The tabledef placeholder specifies the TableDef object representing the attached table whose connection information you want to update.

Remarks

You change the connection information for an attached table by resetting the Connect property of the corresponding TableDef object and then using the RefreshLink method to update the information. When you use RefreshLink, the attached table's properties and Relation objects aren't changed.

To force this connection information to exist in all collections associated with the TableDef object that represents the attached table, you must also use the Refresh method on each collection.


RegisterDatabase Method

Enters connection information for an ODBC data source in the ODBC.INI file. The ODBC driver needs connection information when the Microsoft Jet database engine opens the data source during a session.

Syntax

DBEngine.RegisterDatabase dbname, driver, silent, attributes

The RegisterDatabase method syntax has these parts:

Part	Description

dbname	A string expression that is the name used in the OpenDatabase method that refers to a block of descriptive information about the data source. For example, if the data source is an ODBC remote database, it could be the name of the server.

driver	A string expression that is the name of the ODBC driver. This isn't the name of the ODBC driver DLL file. For example, SQL Server is a driver name, but SQLSRVR.dll is the name of a DLL file. You must have ODBC and the appropriate driver already installed.

silent	A numeric expression that is True if you don't want to display the ODBC driver dialog boxes that prompt for driver-specific information or False if you do want to display the ODBC driver dialog boxes. If silent is True, attributes must contain all the necessary driver-specific information or the dialog boxes are displayed anyway.

attributes	A string expression that is a list of keywords to be added to the ODBC.INI file. The keywords are in a carriage-return–delimited string.

Remarks

If the database is already registered (connection information is already entered) in the ODBC.INI file when you use the RegisterDatabase method, the connection information is updated.

In 32-bit installations, most of the ODBC registration information is maintained in the Windows registration database and not in the ODBC.INI file.

If the RegisterDatabase method fails for any reason, no changes are made to the ODBC.INI file, and an error occurs.

For more information about ODBC drivers such as SQL Server, see the Help file provided with the driver.

You are encouraged to use the Windows Control Panel ODBC setup icon to add new data sources, or to make changes to existing entries. However, if you choose to use the RegisterDatabase method, you are encouraged to set the silent option to True.


RepairDatabase Method

Attempts to repair a corrupted database that accesses the Microsoft Jet database engine.

Syntax

DBEngine.RepairDatabase dbname

The dbname placeholder represents a string expression that is the path and filename for an existing Jet engine database file. If you omit the path, only the current directory is searched. If your system supports the uniform naming convention (UNC), you can also specify a network path, such as: "\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb".

Remarks

You must close the database specified by dbname before you repair it. In a multiuser environment, other users can't have dbname open while you're repairing it. If dbname isn't closed or isn't available for exclusive use, an error occurs.

This method attempts to repair a database that was marked as possibly corrupt by an incomplete write operation. This can occur if an application using the Jet database engine is closed unexpectedly because of a power outage or computer hardware problem. The database won't be marked as possibly corrupt if you use the Close method or if you quit your application in a usual way.

The RepairDatabase method also attempts to validate all system tables and all indexes. Any data that can't be repaired is discarded. If the database can't be repaired, a trappable error occurs.

When you attempt to open or compact a corrupted database, a trappable error usually occurs. In some situations, however, a corrupted database may not be detected, and no error occurs. It's a good idea to provide your users with a way to use the RepairDatabase method in your application if their database behaves unpredictably.

Some types of databases can become corrupted if a user ends an application without closing Database or Recordset objects and the Jet database engine; Microsoft Windows or MS-DOS doesn't have a chance to flush data caches. To avoid corrupt databases, establish procedures for closing applications and shutting down systems that ensure that all cached pages are saved to the database. In some cases, power supplies that can't be interrupted may be necessary to prevent accidental data loss during power fluctuations.

Tip   After repairing a database, it's also a good idea to compact it using the CompactDatabase method to defragment the file and to recover disk space.


Requery Method (DAO)

Updates the data in a Recordset object by re-executing the query on which the object is based.

Syntax

object.Requery [NewQuerydef]

The Requery method syntax has the following parts:

Part	Description

object	The name of an existing table-type Recordset object that has a defined index as specified by the Recordset object's Index property.

NewQuerydef	A Querydef object, which is an optional parameter.

Remarks

Use this method to make sure that a Recordset contains the most recent data. This method re-populates the current Recordset by either using the currrent query parameters or the new ones supplied by the NewQuerydef argument.

·	If the originial Querydef is supplied, then the Recordset is requeried using the parameters specified by the Querydef (for example, myquerydef.OpenRecordset()).

·	If a Querydef was not used to create the recordset, or if a different Querydef is specified than what was originally used to create the Recordset, then the Recordset is essentially re-created from scratch.

When you use Requery, all changes made to the data in the underlying table by other users are displayed in the Recordset, and the first record in the Recordset becomes the current record.

You can't use the Requery method on dynaset- or snapshot-type Recordset objects whose Restartable property is set to False, nor can you use it on a table-type Recordset. However, if you supply the optional NewQueryDef argument, the Restartable property is ignored.

If both the BOF and EOF property settings of the Recordset object are True after you use the Requery method, the query didn't return any records and the Recordset will contain no data.


Seek Method (DAO)

Locates the record in an indexed table-type Recordset object that satisfies the specified criteria for the current index and makes that record the current record.

Syntax

table.Seek comparison, key1, key2...

The Seek method syntax has the following parts.

Part	Description

table	The name of an existing table-type Recordset object that has a defined index as specified by the Recordset object's Index property.

comparison	One of the following string expressions: <, <=, =, >=, or >.

key1, key2...	One or more values corresponding to fields in the Recordset object’s current index, as specified by its Index property setting.

Remarks

You must set the current index with the Index property before you use Seek. If the index identifies a nonunique key field, Seek locates the first record that satisfies the criteria.

Caution   If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without using Update, your changes are lost without warning.

The Seek method searches through the specified key fields and locates the first record that satisfies the criteria specified by comparison and key1. Once found, it makes that record current and the NoMatch property is set to False. If the Seek method fails to locate a match, the NoMatch property is set to True, and the current record is undefined.

If comparison is equal (=), greater than or equal (>=), or greater than (>), Seek starts at the beginning of the index. If comparison is greater than (<) or greater than or equal (<=), Seek starts at the end of the index and searches backward unless there are duplicate index entries at the end. In this case, Seek starts at an arbitrary entry among the duplicate index entries at the end of the index.

You must specify values for all fields defined in the index. If you use Seek with a multi-column index, and you don't specify a comparison value for every field in the index, then you cannot use the equal (=) operator in the comparison. That’s because some of the criteria fields (key2, key3, and so on) will default to NULL, which will probably not match. Therefore, the equal operator will work correctly only if you have a record which is all NULL except the key you're looking for. It’s recommended that you use the greater than or equal operator instead.

The key1 argument must be of the same field data type as the corresponding field in the current index. For example, if the current index refers to a number field (such as Employee ID), key1 must be numeric. Similarly, if the current index refers to a Text field (such as Last Name), key1 must be a string.

There doesn't have to be a current record when you use Seek.

You can use the Indexes collection to enumerate the existing indexes.

Notes

Always check the value of the NoMatch property setting to determine whether the Seek method has succeeded. If it fails, NoMatch is set to True and the current record is undefined.

To locate a record in a dynaset- or snapshot-type Recordset that satisfies a specific condition, use the Find methods. To include all records, not just those that satisfy a specific condition, use the Move methods to move from record to record.

You can't use the Seek method on an attached table of any type because attached tables must be opened as dynaset- or snapshot-type Recordset objects, which don't support the Seek method. However, if you use the OpenDatabase method to directly open an installable ISAM database, you can use Seek on tables in that database.


Synchronize Method

Synchronizes two databases  Various types of exchanges can be performed as specified by the exchange argument. If no argument is provided, the exchange is bidirectional (import and export).

Syntax

database.Synchronize pathname [,exchange]

The Synchronize method syntax has the following parts.

Part	Description

database	An object variable pointing to a replicable Database object that you want synchronized.

pathname	Path to the target database with which database will be synchronized. The trailing .mdb can be optionally omitted.

exchange	A constant indicating which direction to synchronize changes between the two databases. This can be one of the following Integer constants:

  dbRepExportChanges [image] Send changes from database to pathname.

  dbRepImportChanges [image] Receive changes from pathname.

  dbRepImpExpChanges [image] (Default) Bidirectional exchange.

Remarks

This method causes an exchange of data and design changes between the two databases. Design changes are always done first. Both databases must be at the same design level before data can be exchanged. For example, an exchange of type dbRepExportChanges might cause design changes to be made at a replica even though data changes flow only from the database to pathname.

The replica identified in pathname must be part of the same replica set. If both replicas have the same ReplicaID property setting or are Design Masters, the synchronization fails.

Note   The Synchronize method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Update Method

Saves the contents of the copy buffer to a specified dynaset- or table-type Recordset object.

Syntax

recordset.Update

The recordset placeholder represents the name of an open, updatable dynaset- or table-type Recordset object.

Remarks

Use Update to save the current record and any changes you've made to it.

Caution   Changes to the current record are lost if:

You use the Edit or AddNew method, and then move to another record without first using Update.

You use Edit or AddNew, and then use Edit or AddNew again without first using Update.

You set the Bookmark property to another record.

You close the recordset referred to by recordset without first using Update.

You cancel the Edit.

You move off the record.

To edit a record, use the Edit method to copy the contents of the current record to the copy buffer. If you don't use Edit first, an error occurs when you use Update or attempt to change a field's value.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the Update method is executed or the edit is canceled. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it is updated in the database. If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197). Note that optimistic locking is always used on external database formats such as ODBC or installable ISAM. To continue the Update operation with your changes, use the Update method again. To revert to the record as the other user changed it, refresh the current record using the Move methods, or set the Bookmark property to itself, as shown in the following example:

' Error 3197 detected; Restore record from database (as changed).
rstEmployees.BookMark = rstEmployees.Bookmark

To add a new record to a recordset, use the AddNew method.


AbsolutePosition Property

Sets or returns the relative record number of a Recordset object's current record.

Settings and Return Values

The setting or return value is an integer from 0 to one less than the number of records in the Recordset object. It corresponds to the ordinal position of the current record in the Recordset object specified by the object. The data type is Long.

Remarks

The AbsolutePosition property enables you to position the current record pointer to a specific record based on its ordinal position in a dynaset- or snapshot-type Recordset object. You can also determine the current record number by checking the AbsolutePosition property setting.

Because the AbsolutePosition property value is zero-based (that is, a setting of 0 refers to the first record in the Recordset object), it cannot be set to a value greater than or equal to the number of populated records; doing so causes a trappable error. You can determine the number of populated records in the Recordset object by checking the RecordCount property setting. The maximum allowable setting for the AbsolutePosition property is the value of the RecordCount property minus 1.

If there is no current record, as when there are no records in the Recordset object, –1 is returned. If the current record is deleted, the AbsolutePosition property value isn't defined, and a trappable error occurs if it's referenced. New records are added to the end of the sequence.

This property isn't intended to be used as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of Recordset objects. In particular, the position of a given record changes when one or more records preceding it are deleted. There is also no assurance that a given record will have the same absolute position if the Recordset object is re-created again because the order of individual records within a Recordset object isn't guaranteed unless it's created with an SQL statement using an ORDER BY clause.

Note   The AbsolutePosition property isn't available on a forward-only scrolling snapshot type Recordset object, or on a Recordset object opened from a pass-through query against a remote database.


AllowZeroLength Property (DAO)

Sets or returns a value that indicates whether a zero-length string ("") is a valid setting for the Value property of a Field object with a Text or Memo data type. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value is a Boolean expression that indicates if a value is valid. The data type is Boolean. It returns True (-1) if a zero-length string is a valid value.

Remarks

For a Field object, use of the AllowZeroLength property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

You can set this property to False (0) to make sure you can't use a zero-length string to set the Value property of a Field object.

You can use this property along with the Required, ValidateOnSet, or ValidationRule property to determine the validity of a value in a field.


AllPermissions Property

Returns all the permissions that apply to the current UserName property of the Container or Document object, including permissions that are specific to the user as well as the permissions a user inherits from memberships in groups.

Returned Values

For any Container or Document object, the returned values may include the following:

Constant	Description

dbSecReadDef	Can read the table definition including column and index information.

dbSecWriteDef	Can modify or delete the table definition including column and index information.

dbSecRetrieveData	Can retrieve data from the Document object.

dbSecInsertData	Can add records.

dbSecReplaceData	Can modify records.

dbSecDeleteData	Can delete records.

In addition, the Databases Container object or any Document object in a Documents collection may include the following.

Constant	Description

dbSecDeleteData	Can delete records.

dbSecDBAdmin	Gives user permission to make a database replicable and change the database password.

dbSecDBCreate	Can create new databases (valid only on the databases Container object in the system database [System.mdw]).

dbSecDBExclusive	Exclusive access.

dbSecDBOpen	Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

This property contrasts with the Permissions property, which returns only the permissions that are specific to the user and doesn't include any permissions that the user may also have as a member of groups. If UserName is a group, then AllPermissions property returns the same values as Permissions.


Attributes Property

Sets or returns a value that indicates one or more characteristics of a Field object, a Relation object, or a TableDef object. For an object not yet appended to a collection, this property is read/write. For an appended TableDef object, the property is read/write, although not all of the constants may be set if the object is appended, as noted below.

Settings and Return Values

The data type of the setting or return value is Long.

For a Field object, the value specifies characteristics of the field represented by the Field object and can be a sum of these constants:

Constant	Description

dbFixedField	The field size is fixed (default for Numeric fields).

dbVariableField	The field size is variable (Text fields only).

dbAutoIncrField	The field value for new records is automatically incremented to a unique Long integer that can't be changed (supported only for Microsoft Jet database tables).

dbUpdatableField	The field value can be changed.

dbDescending	The field is sorted in descending (Z to A or 100 to 0) order (applies only to a Field object in a Fields collection of an Index object). If you omit this constant, the field is sorted in ascending (A to Z or 0 to 100) order (default).

dbSystemField	The field is a replication field (on a TableDef object) used on replicable databases and cannot be deleted.

For a Relation object, value specifies characteristics of the relationship represented by the Relation object and can be a sum of these constants:

Constant	Description

dbRelationUnique	Relationship is one-to-one.

dbRelationDontEnforce	Relationship isn't enforced (no referential integrity).

dbRelationInherited	Relationship exists in a noncurrent database that contains the two attached tables.

dbRelationUpdateCascade	Updates will cascade.

dbRelationDeleteCascade	Deletions will cascade.

Note   If you set the Relation object's Attributes property to activate cascade operations, the Microsoft Jet database engine automatically updates or deletes records in one or more other tables when changes are made to related primary key tables.

For example, suppose you establish a cascade delete relationship between a Customers table and an Orders table. When you delete records from the Customers table, records in the Orders table related to that customer are also deleted. In addition, if you establish cascade delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

For a TableDef object, value specifies characteristics of the table represented by the TableDef object and can be a sum of these Long constants.

Constant	Description

dbAttachExclusive	For databases that use the Jet database engine, indicates the table is an attached table opened for exclusive use. This constant can be set on an appended TableDef object for a local table, but not for a remote table.

dbAttachSavePWD	For databases that use the Jet database engine, indicates that the user ID and password for the remotely attached table are saved with the connection information. This constant can be set on an appended TableDef object for a remote table, but not for a local table.

dbSystemObject	Indicates the table is a system table provided by the Jet database engine. This constant can be set on an appended TableDef object.

dbHiddenObject	Indicates the table is a hidden table provided by the Jet database engine. This constant can be set on an appended TableDef object.

dbAttachedTable	Indicates the table is an attached table from a non-ODBC database, such as a Microsoft Jet or Paradox database (read-only).

dbAttachedODBC	Indicates the table is an attached table from an ODBC database, such as Microsoft SQL Server (read-only).

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, use of the Attributes property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Read/write until the TableDef object that the Index object is appended to is appended to a Database object; then the property is read-only

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

For a Relation object, the Attributes property setting is read-only for an object appended to a collection.

When setting multiple attributes, you can combine them by summing the appropriate constants. Any nonmeaningful values are ignored without producing an error. For example, to use the Attributes property to make the Text field represented by a new Field object variable-sized and changeable, you can use this code:

fldLastName.Attributes = dbVariableField + dbUpdatableField


BOF, EOF Properties

BOF [image] returns a value that indicates whether the current record position is before the first record in a Recordset object.

EOF [image] returns a value that indicates whether the current record position is after the last record in a Recordset object.

Return Values

The BOF property returns True (-1) if the current record position is before the first record, and False if the current record position is on or after the first record.

The EOF property returns True if the current record position is after the last record, and False (0) if the current record position is on or before the last record.

Remarks

The BOF and EOF properties return values are determined by the location of the current record pointer.

You can use the BOF and EOF properties to determine whether a Recordset object contains records or whether you've gone beyond the limits of a Recordset object as you move from record to record.

If either the BOF or EOF property is True, there is no current record.

If you open a Recordset object containing no records, the BOF and EOF properties are set to True, and the recordset's RecordCount property setting is 0. When you open a Recordset object that contains at least one record, the first record is the current record and the BOF and EOF properties are False; they remain False until you move beyond the beginning or end of the Recordset object using the MovePrevious or MoveNext method, respectively. When you move beyond the beginning or end of the recordset, there is no current record or no record exists.

If you delete the last remaining record in the Recordset object, the BOF and EOF properties may remain False until you attempt to reposition the current record.

If you use the MoveLast method on a Recordset object containing records, the last record becomes the current record; if you then use the MoveNext method, the current record becomes invalid and the EOF property is set to True. Conversely, if you use the MoveFirst method on a Recordset object containing records, the first record becomes the current record; if you then use the MovePrevious method, there is no current record and the BOF property is set to True.

Typically, when you work with all the records in a Recordset object, your code will loop through the records using the MoveNext method until the EOF property is set to True.

If you use the MoveNext method while the EOF property is set to True or the MovePrevious method while the BOF property is set to True, an error occurs.

This table shows which Move methods are allowed with different combinations of the BOF and EOF properties.

	MoveFirst, MoveLast	MovePrevious, Move < 0	Move 0	MoveNext, Move > 0
BOF=True, EOF=False	Allowed	Error	Error	Allowed
BOF=False, EOF=True	Allowed	Allowed	Error	Error
Both True	Error	Error	Error	Error
Both False	Allowed	Allowed	Allowed	Allowed
Allowing a Move method doesn't mean that the method will successfully locate a record. It merely indicates that an attempt to perform the specified Move method is allowed and won't generate an error. The state of the BOF and EOF flags may change as a result of the attempted Move.

Effect of specific methods on the BOF and EOF property settings:

An OpenRecordset method internally invokes a MoveFirst method. Therefore, an OpenRecordset method on an empty set of records results in the BOF and EOF properties being set to True. (See the following table for the behavior of a failed MoveFirst method.)

All Move methods that successfully locate a record clear (set to False) both the BOF and EOF properties.

An AddNew method followed by an Update method that successfully inserts a new record will clear the BOF property, but only if the EOF property is already set to True. The state of the EOF property will always remain unchanged. As defined by the Microsoft Jet database engine, the current record pointer of an empty recordset is at the end of a file, so any new record is inserted after the current record.

Any Delete method, even if it removes the only remaining record from a recordset, won't change the setting of the BOF or EOF property.

The effect of Move methods that don't locate a record on the BOF and EOF property settings is shown in the following table.

	BOF	EOF
MoveFirst, MoveLast	True	True
Move 0	No change	No change
MovePrevious, Move < 0	True	No change
MoveNext, Move > 0	No change	True


Bookmark Property (DAO)

Sets or returns a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset object to a valid bookmark.

Settings and Return Values

The setting or returned value is a string expression or variant expression that evaluates to a valid bookmark. (Data type is Variant array of Byte data.)

Remarks

You can use the Bookmark property with Recordset objects. For a Recordset object based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True and bookmarks can be used. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any Recordset object based on an attached Paradox table that has no primary key.

When a Recordset object is created or opened, each of its records already has a unique bookmark. You can save the bookmark for the current record by assigning the value of the Bookmark property to a variable. To quickly return to that record at any time after moving to a different record, set the Recordset object's Bookmark property to the value of that variable.

There is no limit to the number of bookmarks you can establish. To create a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property to a String variable that identifies the record.

To make sure the Recordset object supports bookmarks, inspect the value of its Bookmarkable property before you use the Bookmark property. If the Bookmarkable property is False, the Recordset object doesn't support bookmarks, and using the Bookmark property results in a trappable error.

If you create a copy of a Recordset object using the Clone method, the Bookmark property settings for the original and the duplicate Recordset objects are identical and can be used interchangeably. However, you can't use bookmarks from different Recordset objects interchangeably, even if they were created using the same object or the same SQL statement.

If you set the Bookmark property to a value that represents a deleted record, a trappable error occurs.

To refresh the contents of a record, set the Bookmark property to itself. (This technique, however, also cancels any pending operations invoked by the Edit or AddNew methods.) For example:

rstCustomers.Bookmark = rstCustomers.Bookmark

The value of the Bookmark property isn't the same as a record number.

Note   The Bookmark property doesn't apply to forward-only scrolling snapshots.


Bookmarkable Property

Returns True (-1) if the Recordset object supports bookmarks, which you can set using the Bookmark property.

Remarks

You can use the Bookmarkable property with Recordset objects.

Check the Bookmarkable property setting before you attempt to set or check the Bookmark property to make sure that the Recordset object supports bookmarks.

For a Recordset object based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True, and bookmarks can be used. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any Recordset object based on an attached Paradox table that has no primary key.

Note   The Bookmarkable property doesn't apply to forward-only scrolling snapshots.


CacheSize, CacheStart Properties

CacheSize [image] sets or returns a value that specifies the number of records in a dynaset-type Recordset object containing data to be locally cached from an ODBC data source.

CacheStart [image] sets or returns a value that specifies the bookmark of the first record in the Recordset object to be cached.

Settings and Returned Values

The setting or return value is a number or string expression. The setting for CacheSize specifies the number of records and must be between 5 and 1200, but not greater than available memory. A typical value is 100. A setting of 0 turns off caching. (Data type is Long.) The setting for CacheStart specifies a bookmark. (Data type is String.)

Remarks

Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type Recordset objects. A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. Data that doesn't come from an ODBC data source isn't saved in the cache.

Any ODBC data source, such as an attached table, can have a local cache. To create the cache, open a Recordset object from the remote data source, set the CacheSize and CacheStart properties, and then use the FillCache method or step through the records using the Move methods.

The CacheSize property setting can be based on the number of records your application can work with at one time. For example, if you're using a Recordset object as the source of the data to be displayed on screen, you could set its CacheSize property to 20 to display 20 records at one time.

The CacheStart property setting is the bookmark of the first record in the Recordset object to be cached. You can use the bookmark of any record to set the CacheStart property. Make the record you want to start the cache with the current record, establish a bookmark for that record, and set the CacheStart property to the bookmark.

The Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Notes

 	Records retrieved from the cache don't reflect changes made concurrently to the source data by other users.

To force an update of all the cached data, set the CacheSize property of the Recordset object to 0, set it to the size of the cache you originally requested, and then use the FillCache method.


Clustered Property

Sets or returns a value that indicates whether an Index object represents a clustering index for a table. This property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Settings and Return Values

The setting or return value is True if the Index object represents a clustering index. The data type is Boolean.

Remarks

A clustering index consists of one or more nonkey fields that, taken together, arrange all records in a table in a predefined order. A clustering index provides efficient access to records in a table in which the index values may not be unique.

Notes

The Clustered property is ignored for databases that use the Microsoft Jet database engine because the Jet database engine doesn't support clustering indexes.

For ODBC databases, the Clustered property always returns False (0); it does not detect whether the ODBC database has a clustering index or not.

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time. The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.


CollatingOrder Property

Returns a value that specifies the sequence of the sort order in text for string comparison or sorting. This property setting is read-only.

Return Values

The possible return values are:

Values	Description

dbSortGeneral	Use the General (English, French, German, Portuguese, Italian, and Modern Spanish) sort order.

dbSortArabic	Use the Arabic sort order.

dbSortCyrillic	Use the Russian sort order.

dbSortCzech	Use the Czech sort order.

dbSortDutch	Use the Dutch sort order.

dbSortGreek	Use the Greek sort order.

dbSortHebrew	Use the Hebrew sort order.

dbSortHungarian	Use the Hungarian sort order.

dbSortIcelandic	Use the Icelandic sort order.

dbSortJapanese	Use the Japanese sort order.

dbSortNeutral	Use the neutral sort order.

dbSortNorwdan	Use the Norwegian or Danish sort order.

dbSortPDXIntl	Use the Paradox International sort order.

dbSortPDXNor	Use the Paradox Norwegian or Danish sort order.

dbSortPDXSwe	Use the Paradox Swedish or Finnish sort order.

dbSortPolish	Use the Polish sort order.

dbSortSpanish	Use the Spanish sort order.

dbSortSwedFin	Use the Swedish or Finnish sort order.

dbSortTurkish	Use the Turkish sort order.

dbSortUndefined	The sort order is undefined or unknown.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, the CollatingOrder property depends on the object that contains the Fields collection, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read only

The CollatingOrder property setting corresponds to the locale argument of the CreateDatabase method when the database was created or the CompactDatabase method when the database was most recently compacted.

Check the CollatingOrder property setting of a Database or Field object to find out the string comparison method for the database or field. You can set the CollatingOrder property of a new Field object if you want the setting of the Field object to differ from that of the Database object that contains it.

The CollatingOrder and Attributes property settings of a Field object in a Fields collection of an Index object together determine the sequence and direction of the sort order in an index. However, you can't set a collating order for an individual index [image] only for an entire table.


ConflictTable Property

Returns the name of a conflict table containing the database records that conflicted during the synchronization of two replicas. The property is read-only and returns a zero-length string if there is no conflict table or the database is non-replicable.

Remarks

If two users at two separate replicas each make a change to the same record in the database, the changes made by one user will fail to be applied to the other replica. Consequently, the user with the failed change must address the problem in a process called "conflict resolution."

Conflict occurs at the record level, not between fields. For example, if one user changes the Address field and another updates the Phone field in the same record, then one change is rejected. Because conflict occurs at the record level, the rejection occurs even though the successful change and the rejected change are unlikely to result in a true conflict of information.

The synchronization mechanism handles the record conflicts by creating conflict tables, which contain the information that would have been placed in the table, if the change had been successful. As a DAO programmer, you examine these conflict tables and work through them row by row, fixing whatever is appropriate.

All conflict tables are named table_conflict, where table is the original name of the table, truncated to the maximum table name length.

Note   The ConflictTable property can be used only if your application has Microsoft Access with Briefcase Replication installed.


Connect Property

Sets or returns a value that provides information about the source of an open database, a database used in a pass-through query, or an attached table. For QueryDef objects, Database objects, attached tables, and TableDef objects not yet appended to a collection, this property setting is read/write. For a base table, this property is read-only.

Syntax

object.Connect = [databasetype;[parameters;]]

The Connect property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

databasetype	A string expression that specifies a database type. For Microsoft Jet databases, exclude this argument; if you specify parameters, use a semicolon (;) as a placeholder. The data type is String.

parameters	A string expression that specifies additional parameters to pass to ODBC or installable ISAM drivers. Use semicolons to separate parameters. The data type is String.

Settings

The Connect property setting is a String composed of a database type specifier and zero or more parameters separated by semicolons. The Connect property is used to pass additional information to ODBC and certain ISAM drivers as needed. It isn't used for Jet databases, except for those containing attached tables, to allow SQL pass-through queries.

To perform an SQL pass-through query on a table attached to your .mdb file, you must first set the Connect property of the attached table's database to a valid ODBC connect string.

For a TableDef object that represents an attached table, the Connect property setting consists of one or two parts (a database type specifier and a path to the database), each of which ends with a semicolon.

The path as shown in the following table is the full path for the directory containing the database files and must be preceded by the identifier "DATABASE=". In some cases (as with Microsoft Excel and Jet databases) a specific filename is included in the database path argument.

The following table shows possible database types and their corresponding database specifiers and paths for the Connect property setting:

Database type	Specifier	Path
Database using the Jet database engine	"[database];"	"drive:\path\filename.mdb"
dBASE III	"dBASE III;"	"drive:\path"
dBASE IV	"dBASE IV;"	"drive:\path"
dBASE 5	"dBASE 5;"	"drive:\path"
Paradox 3.x	"Paradox 3.x;"	"drive:\path"
Paradox 4.x	"Paradox 4.x;"	"drive:\path"
Paradox 5.x	"Paradox 5.x;"	"drive:\path"
FoxPro 2.0	"FoxPro 2.0;"	"drive:\path"
FoxPro 2.5	"FoxPro 2.5;"	"drive:\path"
FoxPro 2.6	"FoxPro 2.6;"	"drive:\path"
Excel 3.0	"Excel 3.0;"	"drive:\path\filename.xls"
Excel 4.0	"Excel 4.0;"	"drive:\path\filename.xls"
Excel 5.0	"Excel 5.0;"	"drive:\path\filename.xls"
Excel 7.0	"Excel 7.0;"	"drive:\path\filename.xls"
Text	"Text;"	"drive:\path"
ODBC	"ODBC; DATABASE=defaultdatabase; UID=user; PWD=password; DSN=datasourcename LOGINTIMEOUT=seconds" (This may not be a complete connection string for all servers; it's just an example.)	None
Remarks

If the specifier is only "ODBC;", a dialog box listing all registered ODBC data source names is displayed by the ODBC driver so the user can select a database.

If a password is required but not provided in the Connect property setting, a login dialog box is displayed the first time a table is accessed by the ODBC driver and again if the connection is closed and reopened.

For Jet database base tables, the Connect property setting is a zero-length string ("").

You can set the Connect property for a Database object by providing a source argument to the OpenDatabase method. You can check the setting to determine the type, path, user ID, Password, or ODBC data source of the database.

For a QueryDef object, you use the Connect property with the ReturnsRecords property to create an ODBC SQL pass-through query. The databasetype of the connection string is "ODBC;", and the remainder of the string contains information specific to the ODBC driver used to access the remote data. For more information, see the documentation for the specific driver.

Note   The Connect property must be set before the ReturnsRecords property is set.


Container Property

Returns the name of the Container object to which a Document object belongs.

Return Values

This property's return value is a String data type.


Count Property (DAO)

Returns the number of objects in a collection.

Return Value

This property's return value is a Long integer data type.

Remarks

Because members of a collection are numbered starting with 0, loops are always coded starting with the 0 member; for example:

For I = 0 to Databases.Count - 1

The Count property setting is never Null. If its value is 0, there are no objects in the collection.


DataUpdatable Property

Returns a value that indicates whether the data in the field represented by a Field object is updatable. Returns a True (-1) if the data in the field is updatable.

Remarks

Use this property to determine whether you can change the Value property setting of a Field object. The DataUpdatable property is always read-only. It is not supported on Field objects appended to the Fields collection of Index and Relation objects.


DateCreated, LastUpdated Properties

DateCreated [image] returns the date and time that the object was created (or the base table if the object is a table-type Recordset object).

LastUpdated [image] returns the date and time of the most recent change made to the object (or the base table if the object is a table-type Recordset object).

Return Values

This property returns a Date/Time data type.

Remarks

You can use the DateCreated and LastUpdated properties with Recordset, TableDef, QueryDef, and Document objects.

For table-type Recordset objects, the date and time settings are derived from the computer on which the base table was created or last updated. For other objects, this property returns the date and time that the object was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies in the DateCreated and LastUpdated property settings.


DefaultUser, DefaultPassword Properties

DefaultUser [image] sets the user name used by the Microsoft Jet database engine when it is initialized.

DefaultPassword [image] sets the password used by the Microsoft Jet database engine when it is initialized.

Settings

The setting for user name can be 1–20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols except for: " (quotation marks), / (forward slash), \ (backslash), [ ] (brackets), : (colon), | (pipe), < (less-than sign), > (greater-than sign), + (plus sign), = (equal sign), ; (semicolon), , ( comma), ? (question mark), * (asterisk), leading spaces, and control characters (ASCII 00 to ASCII 31).

The setting for password can be up to 14 characters long and can contain any character except ASCII 0. The data type is String.

Remarks

User names aren't usually case-sensitive; however, if you're re-creating a user account that was deleted or created in a different workgroup, the user name must be an exact case-sensitive match of the original name. Passwords are case-sensitive.

Typically, the CreateWorkspace method is used to create a Workspace object with a given user name and password. However, for backward compatibility with earlier versions and for convenience when secured databases aren't being used, the Jet engine automatically creates a default Workspace object when needed if one isn't already open. In this case, the DefaultUser and DefaultPassword property values define the user and password for the default Workspace object.

By default, the DefaultUser property is set to “admin” and the DefaultPassword property is set to a zero-length string ("").

For this property to take effect, it should be set before any data access functions are called.


DefaultValue Property (DAO)

Sets or returns the default value of a Field object. For a Field object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value for this property is a string expression, which can contain a maximum of 255 characters. It can be either text or an expression. If the property setting is an expression, it can't contain user-defined functions; Microsoft Jet database engine SQL aggregate functions; or references to queries, forms, or other Field objects.

Note   You can also set the DefaultValue property of a Field object on a TableDef object to a special value called “GenUniqueId( )”. This causes a random number to be assigned to this field whenever a new record is added or created. The field’s Type property must be Long.

Remarks

Use of the DefaultValue property depends on the parent object of the Field objects, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

When a new record is created, the DefaultValue property setting is automatically entered as the value for the field. You can change the field value by setting its Value property.

The DefaultValue property doesn't apply to Counter and OLE Object fields.


Description Property (DAO)

Returns a descriptive string associated with an error.

Remarks

The Description property comprises a short description of the error. Display this property to alert the user to an error that you cannot or do not want to handle.


DistinctCount Property

Returns a value that indicates the number of unique values for the Index object that are included in the associated table.

Return Values

This property returns a Long data type.

Remarks

Check the DistinctCount property to determine the number of unique values, or keys, in an index. Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values. This information is useful in applications that attempt to optimize data access by evaluating index information. The number of unique values is also known as the cardinality of an Index object.

The DistinctCount property won't always reflect the actual number of keys at a particular time. For example, a change caused by a transaction rollback won't be reflected immediately in the DistinctCount property. The number will be accurate immediately after using the CreateIndex method.


EditMode Property

Returns a value that indicates the state of editing for the current record.

Return Values

The return value is an integer that indicates the state of editing. The data type is Integer.

The possible return values are:

Value	Description

dbEditNone	No editing operation is in progress.

dbEditInProgress	Edit method has been invoked, and the current record is in the copy buffer.

dbEditAdd	AddNew method has been invoked, and the current record in the copy buffer is a new record that hasn't been saved in the database.

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Remarks

The EditMode property is most useful when you want to depart from the default functionality of a Data control. You can check the value of the EditMode property and the value of the action parameter in the Validate event procedure to determine whether to invoke the UpdateRecord method.

You can also check to see if the LockEdits property setting is True (-1) and the EditMode property setting is dbEditInProgress to determine whether the current data page is locked.


Filter Property (DAO)

Sets or returns a value that determines the records included in a subsequently opened Recordset object.

Settings and Return Values

A string expression that contains the WHERE clause of an SQL statement without the reserved word WHERE. The data type is String.

Remarks

Use the Filter property to apply a filter to a dynaset- or snapshot-type Recordset object.

You can use the Filter property to restrict the records returned from an existing object when a new Recordset object is opened based on an existing Recordset object.

The following example shows how the Filter property can be used to return only the records for customers who live in a particular region:

rstCustomers.Filter = "Region = 'NY'"
Set rstNYCustomers = rstCustomers.OpenRecordset()

Notes

In many cases, it's faster to open a new Recordset object using an SQL statement that includes a WHERE clause.

Use the U.S. date format (month-day-year) when you filter fields containing dates, even if you're not using the U.S. version of the Microsoft Jet database engine; otherwise, the data may not be filtered as you expect. You can use the Visual Basic Format function to make this easier. For example:

rstEmployees.Filter = "HireDate > #" & Format(mydate, "m/d/yy") & "#"


Foreign Property

Returns a value that indicates whether an Index object represents a foreign key in a table. This property setting is read-only and returns True (-1) if the Index object represents a foreign key.

Remarks

A foreign key consists of one or more fields in a foreign table that uniquely identify all rows in a primary table.

The Microsoft Jet database engine creates an Index object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity.


ForeignName Property

Sets or returns a value that, in a relationship, specifies the name of the Field object in a foreign table that corresponds to a field in a primary table.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a Field in the associated TableDef object's Fields collection.

Remarks

Only a Field object that belongs to a Fields collection contained by a Relation object can support the ForeignName property. If the Relation isn't appended to the Database, but the Field is appended to the Relation, you can still change the ForeignName property. Once the Relation object is appended to the database, the properties of the Field object are read-only.

The Name and ForeignName property value settings for a Field object specify the names of the corresponding fields in the primary and foreign tables of a relationship. The Table and ForeignTable property value argument settings of a Relation object determine the primary and foreign tables of a relationship.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table it must exist in the ValidParts table. If the part code did not exist in the ValidParts table and you had not indicated no enforcement of referential integrity in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a Primary table, so the ForeignTable property of the Relation object would be set to OrderItem and the Table property of the Relation object would be set to ValidParts. The Name property and ForeignName property of the Field object would both be PartNo.


ForeignTable Property

Sets or returns the name of the foreign table in a relationship. This property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in the Relations collection.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a table in the Database object's TableDefs collection. The data type is String.

Remarks

The ForeignTable property setting of a Relation object is the Name property setting of the TableDef or QueryDef object that represents the foreign table or query; the Table property setting is the Name property setting of the TableDef or QueryDef object that represents the primary table or query.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table. If the part code did not exist in the ValidParts table and you had not indicated no enforcement of referential integrity in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to OrderItem. The Name property and ForeignName property of the Field object would both be set to PartNo.


HelpContext, HelpFile Properties (DAO)

HelpContext [image] returns a context ID, as a Long variable, for a topic in a Microsoft Windows Help file.

HelpFile [image] returns a fully qualified path to the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic it identifies.

Note   You should write routines in your application to handle typical errors. When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.


IgnoreNulls Property (DAO)

Sets or returns a value that indicates whether records that have Null values in their index fields have index entries. This property is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Settings and Return Values

This property is a Boolean expression that indicates index entries. The data type is Boolean. True (-1) indicates that the fields with Null values don’t have an index entry.

Remarks

To make searching for records using a field faster, you can define an index for the field. If you allow Null entries in an indexed field and expect many of the entries to be Null, you can set the IgnoreNulls property for the Index object to True to reduce the amount of storage space that the index uses.

The IgnoreNulls property setting and the Required property setting together determine whether a record with a Null index value has an index entry, as the following table shows.

IgnoreNulls	Required	Null in index field

True	False	Null value allowed; no index entry added

False	False	Null value allowed; index entry added

True or False	True	Null value not allowed; no index entry added


Index Property

Sets or returns a value that indicates the name of the current Index object in a table-type Recordset object.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of an Index object in the Indexes collection of the Table or table-type Recordset object's TableDef object. The data type is String.

Remarks

Records in base tables aren't stored in any particular order. Setting the Index property changes the order of records returned from the database; it doesn't affect the order in which the records are stored.

For example, to set the Index property prior to using the Seek method on the Titles table:

Dim rstTitles as Recordset, dbsBiblio as Database

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")

Set rstTitles = dbsBiblio.OpenRecordset("Titles",dbOpenTable)

rstTitles.Index = "PubID"

rstTitles.Seek "=", 3

The specified Index object must already be defined. If you set the Index property to an Index object that doesn't exist or if the Index property isn't set when you use the Seek method, a trappable error occurs.

Examine the Indexes collection of a TableDef object to determine what Index objects are available to table-type Recordset objects created from that TableDef object.

You can create a new index for the table by creating a new Index object, setting its properties, appending it to the Indexes collection of the underlying TableDef object, and then reopening the Recordset object.

Records returned from a table-type Recordset object can be ordered only by the indexes defined for the underlying TableDef object. To sort records in some other order, you can open a dynaset- or snapshot-type Recordset object using an SQL statement with an ORDER BY clause.

Tips

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record or creating a Recordset object can take a long time. On the other hand, creating too many indexes slows down update, append, and delete operations as all indexes are automatically updated.

Records read from tables without indexes are returned in no particular sequence.

The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.

A unique index helps optimize finding records.

Indexes don't affect the physical order of a base table [image] indexes affect only how the records are accessed by the table-type Recordset object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.


Inherit Property

Determines whether new Document objects will inherit a default Permissions property setting.

Return Values

The return values are Boolean data type.

Remarks

Use the Inherit property in conjunction with the Permissions property to define what permissions new documents will automatically be given when they're created. If you set the Inherit property to True (-1), and then set a permission on a container, then whenever a new document is created in that container, that permission will be set on the new document. This is a very convenient way of presetting permissions on an object.

Setting the Inherit property will not affect existing documents in the container [image] you can't modify all the permissions on all existing documents in a container by setting the Inherit property and a new permission. It will affect only new documents that are created after the Inherit property is set.


Inherited Property

Returns a value that indicates whether a Property object is inherited from an underlying object. This property setting is read-only. True (-1) indicates that the Property object is inherited. For built-in Property objects that represent predefined properties, False (0) is the only possible return value.

Remarks

You can use the Inherited property to determine whether a user-defined property was created for the object it applies to or whether the property was created for another object. For example, suppose you create a property for a QueryDef object and then open a Recordset object from the QueryDef object. This property will be part of the Recordset object's Properties collection, and its Inherited property will be set to True because the property was created for the QueryDef object, not the Recordset object.


IniPath Property

Sets or returns the Microsoft Jet database part of the Windows Registry file. This is a change from earlier versions in which options were set in .ini files.

Settings and Return Values

The setting or return value is a string expression that points to a user-supplied portion of the Registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases. The data type is String.

Remarks

The Microsoft Jet engine can be configured with the Registry file. You can use the Registry to set options, such as installable ISAM DLLs.

For this option to have any effect, the IniPath property must be set before any other data access functions are invoked by your application. The scope of this setting is limited to your application and can’t be changed without restarting your application.

You also use the Registry to provide initialization parameters for some installable ISAM database drivers. For example, to use Paradox version 4.0, set the IniPath property to a part of the Registry containing the appropriate parameters.

This property recognizes either HKEY_LOCAL_MACHINE or HKEY_LOCAL_USER. If no root key is supplied, the default is HKEY_LOCAL_MACHINE.


IsolateODBCTrans Property

Sets or returns a value that indicates whether multiple transactions that involve the same ODBC database are isolated.

True (-1) indicates to isolate transactions involving the same ODBC database. False (0) (the default) indicates not to isolate transactions involving the same ODBC database.

Remarks

In some situations, you need to have multiple simultaneous transactions pending on the same ODBC database. To do this, you need to open a separate Workspace for each transaction. Although each Workspace can have its own ODBC connection to the database, this slows system performance. Because transaction isolation isn't normally required, ODBC connections from multiple Workspace objects opened by the same user are shared by default.

Some ODBC servers, such as Microsoft SQL Server, don't allow simultaneous transactions on a single connection. If you need to have more than one transaction at a time pending against such a database, set the IsolateODBCTrans property to True on each Workspace as soon as you open it. This forces a separate ODBC connection for each Workspace.


LastModified Property

Returns a bookmark indicating the most recently added or changed record.

Return Values

The return value is a Variant array of Byte data.

Remarks

You can use LastModified property to move to the most recently added or updated record. Use the LastModified property with Recordset objects. A record must be modified in the Recordset object itself in order for LastModified property to have a value.


LockEdits Property

Sets or returns a value indicating the locking that is in effect during editing.

Settings and Return Values

The setting or return value is a Boolean expression that indicates the type of locking. The data type is Boolean.

The possible settings or return values are:

Setting/Value	Description

True (-1)	(Default) Pessimistic locking is in effect. The 2K page containing the record you're editing is locked as soon as you use the Edit method.

False (0)	Optimistic locking is in effect for editing. The 2K page containing the record is not locked until the Update method is executed.

Remarks

You can use the LockEdits property with dynaset- and table-type Recordset objects.

If a page is locked, no other user can edit records on the same page. If you set LockEdits to True and another user already has the page locked, an error occurs when you use the Edit method. Other users can read data from locked pages.

If you set the LockEdits property to False and later use Update method while the page is locked by another user, an error occurs. To see the changes made to your record by another user, set the Bookmark property of your Recordset object to itself. This approach results in your changes being lost.

When working with ODBC data sources, the LockEdits property is always set to False, or optimistic locking. The Microsoft Jet database engine has no control over the locking mechanisms used in external database servers.


LoginTimeout Property

Sets or returns the number of seconds before an error occurs when you attempt to log in to an ODBC database.

Settings and Return Values

The setting or return value is an Integer representing the number of seconds before a login timeout error occurs. The default LoginTimeout property setting is 20 seconds. When the LoginTimeout property is set to 0, no timeout occurs.

Remarks

When you're attempting to log into an ODBC database, such as SQL Server, the connection can fail as a result of network errors or because the server isn't running. Rather than waiting for the default 20 seconds to connect, you can specify how long the Microsoft Jet database engine waits before it produces an error. Logging on to the server happens implicitly as part of a number of different events, such as running a query on an external server database.

The default timeout value is determined by the current setting of the LoginTimeout property entry in the HKEY_LOCAL_MACHINE\SOFTWARE\Jet\3.0\ODBC key of the Windows Registry.


LogMessages Property (DAO)

Sets or returns a value that specifies if the messages returned from an ODBC database are recorded. This property is user-defined and is read/write once created and installed.

Note   The user must install this property using the CreateProperty method on a QueryDef object.

Settings and Return Values

The setting or return value is a Boolean expression that specifies whether messages are recorded. The data type is Boolean. True indicates that ODBC-generated messages are recorded.

Remarks

Some pass-through queries can return messages in addition to data. If you set the LogMessages property to True (-1), the Microsoft Jet database engine creates a table that contains returned messages. The table name is the user name concatenated with a hyphen (-) and a sequential number starting at 00. For example, because the default user name is ADMIN, the tables returned would be named ADMIN-00, ADMIN-01, and so on.

If you expect the query to return messages, create and append a user-defined LogMessages property for the QueryDef object, and set its type to Boolean and its value to True.

Once you've processed the results from these tables, you may want to delete them from the database along with the temporary query used to create them.


Name Property (DAO)

Sets or returns a user-defined name for a data access object. For an object not appended to a collection, this property is read/write.

Settings and Return Values

The setting or return value is a string expression that specifies a name. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters ( _ ) but can't include punctuation or spaces. The data type is String.

Remarks

TableDef and QueryDef objects can't share the same name, nor can User and Group objects.

The Name property of a Recordset object opened using an SQL statement is the first 256 characters of the SQL statement.

You can use an object's Name property with the Dim statement in code to create other instances of the object.

Note   For many of the Database objects, the Name property reflects the name as known to the Database object, as in the name of a TableDef, Field, or QueryDef object. There is no direct link between the name of the Database object and the object variable used to reference it.

The read/write usage of the Name property depends on the type of object it applies to, and whether or not the object is has been appended to a collection.

Object	Usage

Container	Read-only

Database	Read-only

Document	Read-only

Field

  Unappended	Read/write

  Appended to Index	Read-only

  Appended to QueryDef	Read-only

  Appended to Recordset	Read-only

  Appended to TableDef (native)	Read/write

  Appended to TableDef (linked)	Read-only

  Appended to Relation	Read-only

Group

  Unappended	Read/write

  Appended	Read only

Index

  Unappended	Read/write

  Appended	Read only

Parameter	Read-only

Property

  Unappended	Read/write

  Appended	Read-only

  Built-in	Read-only

QueryDef

  Unappended	Read/write

  Temporary	Read-only

  Appended	Read/write

Recordset	Read-only

Relation

  Unappended	Read/write

  Appended	Read-only

TableDef	Read/write

User

  Unappended	Read/write

  Appended	Read-only

Workspace

  Unappended	Read/write

  Appended	Read-only


NoMatch Property

Returns a value indicating whether a particular record was found using the Seek method or one of the Find methods. True (-1) indicates that the desired record was not found.

Remarks

You can use the NoMatch property with Recordset objects.

When you open or create a Recordset object, its NoMatch property is set to False (0).

To locate a record, use the Seek method on a table-type Recordset object or one of the Find methods on a dynaset- or snapshot-type Recordset object. Check the NoMatch property setting to see whether the record was found.

If the Seek or Find method is unsuccessful and the NoMatch property is True, the current record will no longer be valid. Be sure to obtain the current record's bookmark before using the Seek method or a Find method if you'll need to return to that record.

Note   Using any of the Move methods on a Recordset object won't affect its NoMatch property setting.


Number Property (DAO)

Returns a numeric value specifying an error. The Number property is the Error object's default property.

Return Values

The returned value is a Long Integer representing an error number.

Remarks

Use the Number property to determine the error that occurred. The value of the property corresponds to a unique trap number that corresponds to an error condition. For a complete list of all trap numbers and error conditions, see Trappable Data Access Errors.


ODBCTimeout Property (DAO)

Sets or returns the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is run on an ODBC database.

Settings and Return Values

The setting or return value is an integer representing the number of seconds that the Jet database engine waits before a timeout error occurs. The data type is Integer.

Remarks

When you're using an ODBC database, such as SQL Server, delays can occur because of network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long the Jet database engine waits before it produces an error.

The default timeout value is 60 seconds. When the ODBCTimeout property is set to -1, the default value is used. When the ODBCTimeout property is set to 0, no timeout occurs.

The QueryTimeout property setting for a Database object overrides the default setting.

Setting the ODBCTimeout property of a QueryDef object overrides the values specified by the QueryTimeout property setting of the Database object containing the QueryDef object, but only for that QueryDef object.


OrdinalPosition Property

Sets or returns the relative position of a Field object within the Fields collection to which it is appended. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value is an integer that specifies the numeric order of fields. The default is 0. The data type is Integer.

Remarks

For a Field object, use of the OrdinalPosition property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

Generally, the ordinal position of an object that you append to a collection depends on the order in which you append the object. The first appended object is in the first position (0), the second appended object is in the second position (1), and so on. The last appended object is in ordinal position count –1, where count is the number of objects in the collection as specified by the Count property setting.

Using the OrdinalPosition property, you can specify an ordinal position for new Field objects that differs from the order in which you append those objects to a collection. This enables you to specify a field order for your tables, queries, and recordsets when you use them in an application. For example, the order in which fields are returned in a SELECT * query would be determined by the current OrdinalPosition property values.

You can permanently reset the order in which fields are returned in recordsets by setting the OrdinalPosition property to any positive integer.

Two or more Field objects in the same collection can have the same OrdinalPosition property value, in which case they will be ordered alphabetically. For example, if you have a field named Age set to 4 and you set a second field named Weight to 4, Weight is returned after Age.

You can specify a number that is greater than the number of fields – 1. The field will be returned in an order relative to the largest number. For example, if you set a field's OrdinalPosition property to 20 (and there are only 5 fields) and you've set the OrdinalPosition property for two other fields to 10 and 30, respectively, the field set to 20 is returned between the fields set to 10 and 30.

After you change the OrdinalPosition property setting, you can use the property to return the current setting. However, the fields aren't reordered until the Fields collection is repopulated. For example:

TableDefs("Titles").Fields(0).OrdinalPosition = 3

This code changes which Field object is referenced in the fourth position (0 relative). Because Field(0) was Title, Field(2) now refers to Title, and Field(0) refers to the first (lowest) field in the sequence.

It is simpler to reference Field objects by their Name property. For example, this code assigns the AU_ID field to the third field position:

TableDefs("Titles").Fields("AU_ID").OrdinalPosition = 2

Note   Changing the OrdinalPosition property setting of a Field object in the Fields collection will not immediately change its position in the collection.   You will need to use the Refresh method on the collection to force the Field into its new position. Further, the OrdinalPosition setting is not the same as the field's index within a collection, although they may be equal.


Owner Property

Sets or returns a value that specifies the owner of the object.

Settings and Return Values

The setting or return value is a string expression that evaluates to either the name of a User object in the Users collection or the name of a Group object in the Groups collection. The data type is String.

Remarks

The owner of an object has certain access privileges denied to other users. The Owner property setting can be changed at any time by any individual user account (represented by a User object) or group of user accounts (represented by a Group object) having the appropriate permissions.


Password Property

Sets the password for a user account. This property setting is write-only for new objects not yet appended to a collection, and is not available for existing objects.

Settings

The setting is a string expression that can be up to 14 characters long and can include any characters except the ASCII character 0 (null). The data type is String.

Remarks

Set the Password property along with the PID property when you create a new User object.

Use the NewPassword method to change the Password property setting for an existing User object. To clear a password, set the newpassword argument of the NewPassword method to a zero-length string ("").

Passwords are case-sensitive.

Note   If you don't have access permission, you can't change the password of any other user.


PercentPosition Property

Sets or returns a value that indicates or changes the approximate location of the current record in the Recordset object based on a percentage of the records in the Recordset.

Settings and Return Values

The setting or return value is a number between 0.0 and 100.00. The data type is Single.

Remarks

To indicate or change the approximate position of the current record in a Recordset object, you can check or set the PercentPosition property. When working with a dynaset- or snapshot-type Recordset object, first populate the Recordset object by moving to the last record before you set or check the PercentPosition property. If you use the PercentPosition property before fully populating the Recordset object, the amount of movement is relative to the number of records accessed as indicated by the RecordCount property setting. You can move to the last record using MoveLast method.

Note Using the PercentPosition property to move the current record to a specific record in a Recordset object isn't recommended [image] the Bookmark property is better suited for this task.

Once you set the PercentPosition property to a value, the record at the approximate position corresponding to that value becomes current, and the PercentPosition property is reset to a value that reflects the approximate position of the current record. For example, if your Recordset object contains only five records, and you set its PercentPosition property value to 77, the value returned from the PercentPosition property may be 80, not 77.

The PercentPosition property applies to all three types of Recordset objects, including tables without indexes. The only exceptions are that it does not apply to forward-only scrolling snapshots), or on a Recordset object opened from a pass-through query against a remote database.

You can use the PercentPosition property with a scroll bar on a form or text box to indicate the location of the current record in a Recordset object.


Permissions Property

Sets or returns a value that establishes the permissions for the user or group identified by the UserName property of the Container or Document object.

Settings and Return Values

The setting or return value is a constant that establishes permissions. Possible settings or return values are:

Constant	Description

dbSecNoAccess	No access to the object.

dbSecFullAccess	Full access to the object.

dbSecDelete	Can delete the object.

dbSecReadSec	Can read the object's security-related information.

dbSecWriteSec	Can alter access permissions.

dbSecWriteOwner	Can change the Owner property setting.

For the Tables Container object or any Document object in a Documents collection, the possible settings or return values are:

Constant	Description

dbSecCreate	Can create new documents (valid only with a Container object).

dbSecReadDef	Can read the table definition including column and index information.

dbSecWriteDef	Can modify or delete the table definition including column and index information.

dbSecRetrieveData	Can retrieve data from the Document object.

dbSecInsertData	Can add records.

dbSecReplaceData	Can modify records.

dbSecDeleteData	Can delete records.

For the Databases Container object or any Document object in a Documents collection, the possible settings or return values are:

Constant	User or group

dbSecDBAdmin	Gives user permission to make a database replicable and change the database password.

dbSecDBCreate	Can create new databases (valid only on the databases Container object in the system database [Systen.mdw]).

dbSecDBExclusive	Exclusive access.

dbSecDBOpen	Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Use this property to establish or determine the type of read/write/modify permissions the user has for a Container or Document object.

A Document object inherits the permissions for users from its Container object, provided the Inherited property of the Container object is set for those users or for a group to which the users belong. By setting a Document object's Permissions and UserName properties later, you can further refine the access control behavior of your object.


PID Property

Sets the personal identifier (PID) for either a group or a user account. This property setting is write-only for new objects not yet appended to a collection, and is not available for existing objects.

Settings

The setting is a string expression containing 4-20 alphanumeric characters. The data type is String.

Remarks

Set the PID property along with the Name property when you create a new Group object. Set the PID property along with the Name and Password properties when you create a new User object.


Primary Property (DAO)

Sets or returns a value that indicates whether an Index object represents a primary index for a table. The Primary property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection. If the Index object is appended to the TableDef object but the TableDef object isn't appended to the TableDefs collection, the Index property is read-write.

Settings and Return Values

The setting or return value is a Boolean expression that specifies a primary index. The data type is Boolean. True (-1) indicates that the Index object represents a primary index.

Remarks

A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the index field must be unique, the Unique property of the Index object is set to True. If the primary index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and usually contains the same fields as the primary key.

Tip   You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time. The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index. When you create a new table in your database, it's a good idea to create an index on one or more fields that uniquely identify each record, and then set the Primary property of the Index object to True.

When you set a primary key for a table, the primary key is automatically defined as the primary index for the table.


QueryTimeout Property

Sets or returns a value that specifies the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is executed on an ODBC database.

Settings and Return Values

The setting or return value is an integer representing the number of seconds the Jet database engine waits before timing out and returning an error. The data type is Integer.

Remarks

When you're using an ODBC database, such as SQL Server, there may be delays due to network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long to wait before the Jet database engine produces an error.

When used with a Database object, the QueryTimeout property specifies a global value for all queries associated with the database.

The timeout value is taken from the Windows Registry. If there is no Windows Registry setting, the default value is 60 seconds. Once this property is set, however, it overrides any Windows Registry setting or default value.


RecordCount Property

Returns the number of records accessed in a Dynaset-type or Snapshot-type Recordset object, or the total number of records in a Table-type Recordset or TableDef object. This property setting is read-only.

Return Values

The return value is a Long Integer.

Remarks

Use the RecordCount property to find out how many records in a Recordset or TableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset- or snapshot-type Recordset object until all records have been accessed.

Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef object. To force the last record to be accessed, use the MoveLast method on the Recordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.

As your application deletes records in a dynaset-type Recordset object, the value of the RecordCount property decreases. However, records deleted by other users aren't reflected by the RecordCount property until the current record is positioned to a deleted record. If you execute a transaction that affects the RecordCount property setting and subsequently rolls back the transaction, the RecordCount property won't reflect the actual number of remaining records.

The RecordCount property of a snapshot-type Recordset object isn't affected by changes in the underlying tables.

A Recordset or TableDef object with no records has a RecordCount property setting of 0.

When working with attached TableDef objects, the RecordCount property setting is always –1.

Using the Requery method on a Recordset object resets the RecordCount property just as if the query were re-executed.


RecordsAffected Property

Returns the number of records affected by the most recently invoked Execute method.

Return Values

The return value is an integer from 0 to the number of records affected by the most recently invoked Execute method on either a Database or QueryDef object. The data type is Long.

Remarks

The RecordsAffected property contains the number of records deleted, updated, or inserted when running an action query. When you use the Execute method to run a QueryDef object, the RecordsAffected property setting is the number of records affected.

Note   The RecordsAffected property setting is the same as the value returned by the ExecuteSQL method.


Required Property (DAO)

Sets or returns a value that indicates whether a Field object requires a non-Null value or whether all the fields in an Index object must be filled in. For an object not yet appended to a collection, this property is read/write. For an Index object, this property setting is read-only for objects appended to Indexes collections in Recordset and TableDef objects.

Settings and Return Values

The setting or return value is a Boolean expression indicating whether an object requires a non-Null value. True indicates that a Null value is not allowed.

Remarks

For a Field object, use of the Required property depends on its parent object, as shown in the following table.

Parent Object	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

For a Field object, you can use the Required property along with the AllowZeroLength, ValidateOnSet, or ValidationRule property to determine the validity of the Value property setting for that Field object. If the Required property is set to False (0), the field can contain Null values as well as values that meet the conditions specified by the AllowZeroLength and ValidationRule property settings.

Tip   When you can set this property for either an Index object or a Field object, set it for the Field object. The validity of the property setting for a Field object is checked before that of an Index object.


Restartable Property

Returns a value that indicates whether a Recordset object supports the Requery method, which reexecutes the query on which the Recordset object is based.

Return Values

The possible return values are:

Value	Description

True	The Recordset object supports the Requery method.

False	The Recordset object doesn't support the Requery method. Table-type Recordset objects always return False (0).

Remarks

Check the Restartable property before using the Requery method on a Recordset object. If the object's Restartable property is set to False, use the OpenRecordset method on the underlying QueryDef object to re-execute the query.

You can use the Requery method to update a Recordset object's underlying parameter query after the parameter values have been changed.


ReturnsRecords Property (DAO)

Sets or returns a value that indicates whether an SQL pass through query to an external database returns records.

Settings and Return Values

A Boolean expression that indicates whether records are returned. The data type is Boolean. True (-1) (the default) indicates that a pass-through query returns records.

Remarks

Not all SQL pass-through queries to external databases return records. For example, an SQL UPDATE statement updates records without returning records, while an SQL SELECT statement does return records. If the query returns records, set the ReturnsRecords property to True; if the query doesn't return records, set the ReturnsRecords property to False (0).

Note   The Connect property must be set before the ReturnsRecords property is set.


Size Property

Returns a value that indicates the maximum size, in bytes, of a Field object. For Text fields, you can also use it to set the maximum size of data that the Field object can hold. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value indicates the maximum size of a Field object. The data type is Long. The setting depends on the Type property setting of the Field object and can be one of these integer values.

Type	Size	Description

dbBoolean	1	Boolean

dbByte	1	Byte

dbInteger	2	Integer

dbLong	4	Long

dbCurrency	8	Currency

dbSingle	4	Single

dbDouble	8	Double

dbDate	8	Date/Time

dbText	1–255	Text

dbLongBinary	0	Long Binary (OLE Object)

dbMemo	0	Memo

dbGUID	16	GUID

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Use of the Size property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read-only

When you create a Field object with a data type other than Text, the Type property setting automatically determines the Size property setting, and you don't need to set the Size property. For a Field object with the Text data type, however, Size can be set to any integer up to the maximum text size (for Microsoft Jet databases that maximum is 255). If you do not set the size, the field will be as large as the database allows.

For OLE Object and Memo Field objects, Size is always set to 0. Use the FieldSize method of the Field object to determine the size of the data in a specific record. The maximum size of an OLE Object or Memo field is limited only by your system resources or the maximum size that the database allows.


Sort Property

Sets or returns the sort order for records in a Recordset object.

Settings and Return Values

The setting or return value is a string expression that contains the ORDER BY clause of an SQL statement without the reserved words ORDER BY. (Data type is String.)

Remarks

You can use the Sort property with dynaset- and snapshot-type Recordset objects.

When you set this property for an object, sorting occurs when a subsequent Recordset object is created from that object. The Sort property setting overrides any sort order specified for a QueryDef object.

The default sort order is ascending (A to Z or 0 to 100). The following examples show how you can set the sort order to ascending or descending (Z to A or 100 to 0):

rstOrders.Sort = "ShipCountry"	' Defaults to ascending.

rstOrders.Sort = "ShipCountry Asc"	' Ascending.

rstOrders.Sort = "ShipCountry Desc"	' Descending.

The Sort property doesn't apply to table-type Recordset objects. To sort a table-type Recordset object, use the Index property.

Tip   In many cases, it's faster to open a new Recordset object using an SQL statement that includes the sorting criteria.


Source Property (DAO)

Returns the name of the object or application that originally generated the error.

Return Values

The return value is a string expression representing the object or application that generated the error.

Remarks

The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object's class name or programmatic ID. Use the Source property to provide your users with information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Error.Number to its error code for that error and sets the Source property to Excel.Application. Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and sets Error.Number to its own code for Division by zero. However, it leaves the other Error object properties (including the Source property) as set by the object that generated the error. The Source property always contains the name of the object that originally generated the error [image] your code can try to handle the error according to the error documentation of the object you accessed. If your error handler fails, you can use the Error object information to describe the error to your user, using the Source property and the other Error properties to inform the user which object originally caused the error, its description of the error, and so forth.

Note   The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects. Checking the Error object property after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred. Thus, you can be sure which object placed the error code in Error.Number, as well as which object originally generated the error (the one specified in Error.Source).


SourceField, SourceTable Properties

SourceField [image] returns a value that indicates the name of the field that is the original source of the data for a Field object.

SourceTable [image] returns a value that indicates the name of the table that is the original source of the data for a Field object.

This property is not available at design time and is read-only at run time.

Return Values

The return value is a string expression specifying the name of the field or table that is the source of data. The data type is String.

Remarks

For a Field object, use of the SourceField and SourceTable properties depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read-only

These properties indicate the original field and table names associated with a Field object. For example, you could use these properties to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table.


SourceTableName Property

Sets or returns a value that specifies the name of an attached table or the name of a base table. This property setting is read-only for a base table and read/write for an attached table or an object not appended to a collection.

Settings and Return Values

The setting or return value is a string expression that specifies a table name. For a base table, the setting is a zero-length string (""). The data type is String.


SQL Property

Sets or returns the SQL statement that defines the query executed by a QueryDef object.

Settings and Return Values

The setting or return value is a string expression that contains an SQL statement. The data type is String.

Remarks

The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you execute the query. You can use the query to select records to include in a dynaset- or snapshot-type Recordset object. You can also define bulk queries to modify data without returning records.

Using the ORDER BY or WHERE clause to sort or filter a Recordset object is more efficient than using the Sort and Filter properties.

The SQL syntax used in a query must conform to the SQL dialect as defined by the Microsoft Jet database engine unless you create an SQL pass through query.

Using a QueryDef object is the preferred way to perform SQL pass through operations on ODBC databases. By setting the QueryDef object's Connect property to an ODBC data source, you can specify non-Microsoft Jet database SQL in the query passed to the external server. For example, you can use TRANSACT SQL statements (with Microsoft SQL Server or Sybase SQL Server databases) in the value argument, which won't be processed by the Jet database engine.

If the SQL statement includes parameters for the query, you must set these before you execute the query. Until you reset the parameters, the same parameter values are applied each time you execute the query. Set the parameters by accessing the Parameters collection of the QueryDef object using the following code.

qdfOrders.Parameters("Order Date") = "10/11/94"   ' Set parameters.

qdfOrders.Parameters("Ship Date") = "11/4/94"


Table Property

Sets or returns a value that specifies the name of a Relation object's primary table. This name is the Name property setting of a TableDef or QueryDef object. The Table property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in a Relations collection.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a table in the TableDefs collection. The data type is String.

Remarks

Use the Table property with the ForeignTable property to define a Relation object, which represents the relationship between fields in two tables or queries. Set the Table property to the Name property setting of the primary TableDef or QueryDef object, and set the ForeignTable property to the Name property setting of the foreign (referencing) TableDef or QueryDef object. The Attributes property determines the type of relationship between the two objects.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table. If the part code didn't exist in the ValidParts table and you had not indicated No Enforcement in the Attributes property, a trappable error would occur.

In this case, the ValidParts table is an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to the OrderItem table. The Name property and ForeignName property of the Field object would both be set to PartNo.

The following illustration shows how the ValidParts table is primary because it's referenced by the OrderItem table.


Transactions Property

Returns a value that indicates whether an object supports the recording of a series of changes that can later be rolled back (canceled) or committed (saved). True (-1) indicates that the object supports transactions. Snapshot-type Recordset objects always return False (0).

Remarks

You can use the Transactions property with dynaset- or snapshot-type Recordset objects.

If a dynaset or table is based on a Microsoft Jet database engine table, the Transactions property is True and you can use transactions. Other database engines may not support transactions. For example, you can't use transactions in a dynaset-type Recordset object based on a Paradox table.

Check the Transactions property before using the BeginTrans method on the Recordset object's Workspace object to make sure that transactions are supported. Using the BeginTrans, CommitTrans, or Rollback methods on a nonsupported object has no effect.


Type Property (DAO)

Sets or returns a value that indicates the operational type or data type of an object. For a Field or Property object, this property is read/write until the object is appended to a collection or to another object, after which it's read-only. For a Parameter, QueryDef, or Recordset object, the property setting is read-only.

Settings and Return Values

The setting or return value is a constant that indicates an operational or data type. The data type is Integer.

For a Field, Parameter, or Property object, the possible settings and return values are:

Setting/Value	Description

dbBoolean	Boolean

dbByte	Byte

dbInteger	Integer

dbLong	Long

dbCurrency	Currency

dbSingle	Single

dbDouble	Double

dbDate	Date/Time

dbText	Text

dbLongBinary	Long Binary (OLE Object)

dbMemo	Memo

dbGUID	GUID

For a QueryDef object, the possible settings and return values are:

Setting/Values	Query type

dbQSelect	Select

dbQAction	Action

dbQCrosstab	Crosstab

dbQDelete	Delete

dbQUpdate	Update

dbQAppend	Append

dbQMakeTable	Make-table

dbQDDL	Data-definition

dbQSQLPassThrough	Pass-through

dbQSetOperation	Union

dbQSPTBulk	Used with dbQSQLPassThrough to specify a query that doesn't return records.

Note   To create an SQL pass through query, don't set the dbQSQLPassThrough constant. This is set automatically by the Microsoft Jet database engine when you create a QueryDef object and set the Connect property.

For a Recordset object, the possible settings and return values are:

Setting	Recordset type

dbOpenTable	Table

dbOpenDynaset	Dynaset

dbOpenSnapshot	Snapshot

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Depending on the object, the Type property indicates:

Object	Type indicates

Field, Parameter, Property	Object data type

QueryDef	Type of query

Recordset	Type of Recordset object

When you append a new Field, Parameter, or Property object to the collection of an Index, QueryDef, Recordset, or TableDef object, an error occurs if the underlying database doesn't support the data type specified for the new object.


Unique Property

Sets or returns a value that indicates whether an Index object represents a unique (key) index for a table. For an Index object, this property setting is read/write until the object is appended to a collection, after which it's read-only.

Settings and Return Values

The setting or return value is a Boolean expression that specifies a unique index. The data type is Boolean. True (-1) indicates that the Index object represents a unique index.

Remarks

A unique index consists of one or more fields that logically arrange all records in a table in a unique, predefined order. If the index consists of one field, values in that field must be unique for the entire table. If the index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.

If both the Unique and Primary properties of an Index object are set to True, the index is unique and primary: It uniquely identifies all records in the table in a predefined, logical order. If the Primary property is set to False (0), the index is a secondary index. Secondary indexes (both key and nonkey) logically arrange records in a predefined order without serving as an identifier for records in the table.

Tips

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.

Records read from tables without indexes are returned in no particular sequence.

The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that Index object.

A unique index helps optimize finding records.

Indexes don't affect the physical order of a base table [image] indexes affect only how the records are accessed by the table-type Recordset object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.


Updatable Property

Returns a value that indicates whether changes can be made to a data access object. True (-1) indicates that the object can be changed or updated. (Snapshot-type Recordset objects always return False (0).)

Remarks

Depending on the object, if the Updatable property setting is True, the specified:

Database object can be changed.

QueryDef object query definition can be changed.

Recordset object records can be updated.

TableDef object table definition can be changed.

You can use the Updatable property with all Recordset objects.

The Updatable property setting is always True for a newly created TableDef object and False for an attached TableDef object. A new TableDef object can be appended only to a database for which the current user has write permission.

Many types of objects can contain fields that can't be updated. For example, you can create a dynaset-type Recordset object in which only some fields can be changed. These fields can be fixed or contain data that increments automatically, or the dynaset can result from a query that combines updatable and nonupdatable tables.

If the object contains only nonupdatable fields, the value of the Updatable property is False. When one or more fields are updatable, the property's value is True. You can edit only the updatable fields. A trappable error occurs if you try to assign a new value to a nonupdatable field.

The Updatable property of a QueryDef object is set to True if the query definition can be updated, even if the resulting Recordset object isn't updatable.

Because an updatable object can contain nonupdatable fields, check the Fields collection of a Recordset object to check the DataUpdatable property of each field before you edit a record in the Recordset object.


UserName Property

Sets or returns a value that represents a user or group of users or the owner of a Workspace object. For Container and Document objects, this property setting is read/write. For a Workspace object, this property setting is read/write for an object not yet appended to a collection and read-only for an existing Workspace object.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a User object in the Users collection or a Group object in the Groups collection. (Data type is String.)

Remarks

Depending on the type of object, the UserName property represents:

A user or group of users when you manipulate the access permissions of a Container object or a Document object.

The owner of a Workspace object. For Container and Document objects, you use the UserName property with the Permissions property to establish read or write permissions.

To find or set the permissions for a particular user or group of users, first set the UserName property to the user or group name that you want to examine. Then check the Permissions property setting to determine what permissions that user or group of users has, or set the Permissions property to change the permissions.

For a Workspace object, check the UserName property setting to determine the owner of the Workspace object. Set the UserName property to establish the owner of the Workspace object before you append the object to the Workspaces collection.


V1xNullBehavior Property (DAO)

Sets or returns a value that indicates whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null. This property applies to Microsoft Jet database engine version 1.x databases that have been converted to Jet database engine version 2.0 or 3.0 databases.

Note   The Jet database engine automatically creates this property when it converts a version 1.x database to a version 2.0 or 3.0 database. A 2.0 database will retain this property when it is converted to a 3.0 database.

Settings and Return Values

The setting or return value is a Boolean expression that indicates whether zero-length strings are converted to Null. The data type is Boolean. True (-1) indicates that zero-length strings are converted to Null.

Remarks

If you change this property setting, you must close and then reopen the database for your change to take effect.

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so that the fields are set to Null instead, and remove the V1xNullBehavior property from the Properties collection.


ValidateOnSet Property

Sets or returns a value that specifies whether or not the value of a Field object is immediately validated when the object's Value property is set. Only Field objects in Recordset objects support the ValidateOnSet property as read/write.

Settings and Return Values

The setting or return value is a Boolean expression that indicates whether a value is validated, as described in Settings. The data type is Boolean. The possible settings or return values are:

Setting/Value	Description

True	Validate when the property is set.

False	Validate when the record is updated.

Remarks

When the ValidateOnSet property is set to True (-1), the validation rule specified by the ValidationRule property setting of the Field object is checked when you set the object's Value property.

When the ValidateOnSet property is set to False (0), you can set the Value property of each field independently and perform validation using the final value settings when the record is updated.


ValidationRule Property (DAO)

Sets or returns a value that validates the data in a field as it's changed or added to a table. For an object not yet appended to the Fields collection, this property is read/write. See Remarks for the more specific read/write characteristics of this property.

Settings and Return Values

The settings or return values is a string expression that describes a comparison in the form of an SQL WHERE clause without the WHERE reserved word. The data type is String.

Remarks

The ValidationRule property determines whether or not valid data is in the associated field. If the data is not legal, a trappable run-time error occurs. The returned error message is the text of the ValidationText property, if specified, or the text of the expression specified by ValidationRule.

For a Field object, use of the ValidationRule property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

For a Recordset object, use of the ValidationRule property is read-only. For a TableDef object, use of the ValidationRule property depends on the status of the TableDef object, as the following table shows.

TableDef	Usage

Base table	Read/write

Attached table	Read-only

Validation is supported only for databases that use the Microsoft Jet database engine.

The string expression specified by the ValidationRule property of a Field object can refer only to that Field. The expression can't refer to user-defined functions, SQL aggregate functions, or queries. To set a Field object's ValidationRule property when its ValidateOnSet property setting is True, the expression must successfully parse (with the field name as an implied operand) and evaluate to True. If its ValidateOnSet property setting is False, the ValidationRule property setting is ignored.

The ValidationRule property of a Recordset or TableDef object can refer to multiple fields in that object. The restrictions noted earlier in this topic for the Field object apply.

For a table-type Recordset object, the ValidationRule property takes the value of the ValidationRule property setting of the TableDef object that you use to create the table-type Recordset object.

For a TableDef object based on an attached table, the ValidationRule property takes the value of the underlying base table. If the underlying base table doesn't support validation, the value of this property is a zero-length string ("").


ValidationText Property (DAO)

Sets or returns a value that specifies the text of the message that your application displays if the value of a Field object doesn't satisfy the validation rule specified by the ValidationRule property setting.

For an object not yet appended to a collection, this property is read/write. For a Recordset object, this property setting is read-only. For a TableDef object, this property setting is read-only for an attached table and read/write for a base table.

Settings and Return Values

The setting or return value is a string expression that specifies the text displayed if an entered value is invalid. The data type is String.

Remarks

For a Field object, use of the ValidationText property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write


Value Property (DAO)

Sets or returns the value of an object.

Settings and Return Values

The setting or return value is an expression that evaluates to a value appropriate for the data type, as specified by the Type property of an object. The data type is Variant.

Remarks

Generally, the Value property is used to retrieve and alter data in Recordset objects.

The Value property is the default property of the Field, Parameter, and Property objects. Therefore, the following lines of code are equivalent (assuming Field1 is at the first ordinal position).

varX = rstProducts!Field1

varX = rstProducts!Field1.Value

varX = rstProducts(0)

varX = rstProducts(0).Value

varX = rstProducts("Field1").Value

varX = rstProducts("Field1")

F$ = "Field1" : varX = rstProducts(F$).Value

varX = rstProducts(F$)


Version Property

Returns a value that indicates the version of the database or database engine associated with the object. This property setting is read-only.

Return Values

The return value is a string expression that evaluates to a value, depending on the object specified:

Database object [image] identifies the data format version of an open database.

DBEngine object [image] identifies the version number of the Microsoft Jet database engine.

Remarks

For a Database object, this property identifies the version of the Jet database engine that created the database.

The setting of the Version property represents the version number in the form "major.minor"; for example, "3.0". The product version number (for example, 3.0) consists of the version number (2), a period, and the release number (0).

Note   The Version property corresponds to the version of the Microsoft Jet database engine, and doesn’t necessarily match the version number of the Microsoft product with which the database engine is included.  For example, the Version property of a database object created with Microsoft Visual Basic 3.0 will be 1.1, not 3.0.

The following table shows which version of the database engine is used with various versions of the Microsoft products that feature the engine:

Jet Engine	Access	Visual Basic	Excel	Developer’s Studio

Version	Version	Version	Version	(Visual C++) Version

1.0 (1992)	1.0	-	-	-

1.1 (1993)	1.1	3.0	-	-

2.0 (1994)	2.0	-	-	-

2.5 (1995)	-	4.0 (16-bit)	-	-

3.0 (1995)	‘95 (7.0)	4.0 (32-bit)	‘95 (7.0)	4.0


KeepLocal Property

Sets or returns a value on a TableDef or QueryDef object, or a table, query, form, report, macro, or module that you do not want made replicable when the database is converted to a replicable form.

Note   The user must install this property using the CreateProperty method on a QueryDef object.

Setting and Return Value

You set this property to the text string "T" to keep the object local while all other objects are made replicable when the database is made replicable. The KeepLocal property cannot be applied to objects after they have been converted into a replicable form.

Remarks

On Database, TableDef, and QueryDef objects, you create and append the KeepLocal property to the object's properties collection.

On forms, reports, macros, and modules defined by a host application (such as Microsoft Access for Windows 95), you create and append the KeepLocal property to the properties collection of the document object representing the object. For example, the following code appends the KeepLocal property to the properties collection of a document object for a module:

Dim dbs as database, doc as document, prp as property

Set dbs = currentdb

set doc = dbs.Containers!Modules.Documents![Utility Functions]

set prp = doc.CreateProperty("KeepLocal", dbText, "T")

doc.properties.append prp

Before setting the KeepLocal property, your code should check the value of the Replicable property.

Local objects remain at the replica where they were created and are not propagated around the replica set. Each time you make a new replica in the set, all the replicable objects at the source replica are included in that new replica, but none of the local objects are included.

The object on which you are setting the KeepLocal property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to KeepLocal. You must directly set the property for each object.


Replicable Property

Sets or returns a value that determines whether a database or object in a database can be replicated.

On a Database object, this property adds fields, tables, and properties to a database

On a TableDef or QueryDef object, or table, query, form, report, macro, or module in a database, this property changes the object from local to replicable.

Note   The user must install this property using the CreateProperty method on a QueryDef object.

Setting and Return Values

On a Database object, setting this property to the text string "T" makes the database replicable. Once the property is set to "T", it cannot be changed; setting the property to "F" (or any value other than "T") returns an error message.

On an object in a database, setting this property to the text string "T" makes the object (and subsequent changes to the object) available at all replicas in the replica set. You can also set this property in the object's property sheet in Microsoft Access.

Remarks

Before setting the Replicable property on a database, make a back-up copy of the database. If setting the Replicable property fails, you should delete the partially replicated database, make a new copy from the back-up, and try again.

On Database, TableDef, and QueryDef objects, you create and append the Replicable property to the object's properties collection.

On forms, reports, macros, and modules defined by a host application (such as Microsoft Access for Windows 95), you create and append the Replicable property to the properties collection of the document object representing the object. For example, the following code appends the Replicable property to the properties collection of a document object for a module:

Dim dbs as database, doc as document, prp as property

Set dbs = currentdb

set doc = dbs.Containers!Modules.Documents![Utility Functions]

set prp = doc.CreateProperty("Replicable", dbText, "T")

doc.properties.append prp

If the Replicable property has already been set on an object using the Replicated check box in the Properties dialog for the object, the Replicable property cannot be set in code.

When you create a new table, query, form, report, macro, or module at a replica, the object is considered "local" and is stored only at that replica. If you want users at other replicas to be able to use the object, you must change it from local to replicable. Either create the object at, or import it into, the Design Master and then set the Replicable property to "T".

The object on which you are setting the Replicable property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to make replicable. You must directly set the property for each object.


ReplicaID Property

Returns a 16-byte, OLE 2 GUID that provides each database replica with a unique identification.

Setting and Return Values

This property is read-only and the value is created by the Microsoft Jet database engine.

Remarks

In addition to providing a unique identifier for each database replica, the ReplicaID property is used to identify the Design Master for the replica set. The ReplicaID property of the Design Master is stored in the MSysReplicas system table. Setting the DesignMasterID property gives a specific replica in the replica set design-master status. The DesignMasterID property can be set only if you are at the current Design Master. Under extreme circumstances, for example, the loss of the original Design Master, you can set the value at another replica. However, setting this value at a replica, when there is already another Design Master, might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.


DesignMasterID Property

Sets or returns a 16-byte, OLE 2 GUID, created by the Microsoft Jet database engine, that uniquely identifies the Design Master in a replica set.

Remarks

The DesignMasterID property setting is stored in the MSysRepInfo system table. Setting the DesignMasterID property makes a specific replica in the replica set the Design Master. The DesignMasterID property can be set only if you are at the current Design Master. Under extreme circumstances, for example, the loss of the original Design Master, you can set the value at another replica. However, setting this value at a replica, when there is already another Design Master, might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

Warning   This property should be set only at the current Design Master. Setting this property at a replica, when there is already another Design Master, can partition your replica set into two irreconcilable sets and prevent any further synchronization of data. You can set the property at another replica only if the original Design Master is lost or erased. This will designate the current replica as the new Design Master.


SystemDB Property

Sets or returns the path for the current location of the system database file.

Settings and Return Values

The setting or return value is a string expression describing the fully-resolved path. The data type is String.

Remarks

For this option to have any effect, the SystemDB property must be set before the DBEngine object is initialized (i.e., by creating an instance of any other data access object) by your application. The scope of this setting is limited to your application and can’t be changed without restarting your application.


SystemDB Property Example

This example sets the SystemDB property, then initializes the DBEngine object.

DBEngine.SystemDB = "C:\Windows\System\System.mdb"

‘ You can now instantiate other DAO objects, thus initializing DBEngine

Dim dbsCurrent As Database, rstEmployees As Recordset

Set dbsCurrent As DBEngine.Workspaces(0).OpenDatabase("MyDbs.mdb")

...

...


Data Access Constants

You can use the Object Browser to view a list of built-in constants. From the View menu, choose Object Browser, select the appropriate library, and then select the Constants object. Scroll the list in the Methods/Properties box to see the complete list of constants.

The data access objects provide built-in constants that you can use with methods or properties. These constants all begin with the letters db and are documented with the method or property to which they apply.

The Microsoft Jet database engine contains built-in constants that you can use with methods or properties. These constants all begin with the letters db and are documented with the method or property to which they apply.

Legend:

Read-only

Read/write

Attributes Property Constants

Field.Attributes Property

Constant	Description

dbFixedField	Field size fixed (default for Numeric fields).

dbVariableField	Field size variable (Text fields only).

dbAutoIncrField	New record field value incremented to unique Long integer (Counter type).

dbUpdatableField	Field is updatable.

dbDescending	Field sorted in descending order.

dbSystemField	The field is a replication field (on a TableDef object).

Relation.Attributes Property

Constant	Description

dbRelationUnique	One-to-one relationship.

dbRelationDontEnforce	Relationship not enforced (no referential integrity).

dbRelationInherited	Relationship exists in the database containing the two attached tables.

dbRelationUpdateCascade	Updates cascade.

dbRelationDeleteCascade	 Deletions cascade.

TableDef.Attributes Property

Constant	Description

dbAttachExclusive	 Attached Microsoft Jet database engine table opened for exclusive use.

dbAttachSavePWD	Save user ID and password for attached remote table.

dbSystemObject	System table.

dbHiddenObject	Hidden table (for temporary use).

dbAttachedTable	Attached non-ODBC database table.

dbAttachedODBC	Attached ODBC database table.

CollatingOrder Property Constants (All are [image])

Constant	Description

dbSortArabic	Arabic collating order.

dbSortCyrillic	Russian collating order.

dbSortCzech	Czech collating order.

dbSortDutch 	Dutch collating order.

dbSortGeneral	English, German, French, and Portuguese collating order.

dbSortGreek	Greek collating order.

dbSortHebrew	Hebrew collating order.

dbSortHungarian	Hungarian collating order.

dbSortIcelandic	Icelandic collating order.

dbSortJapanese	Japanese collating order.

dbSortNeutral	Neutral collating order.

dbSortNorw	Norwegian and Danish collating order.

dbSortPDXIntl	Paradox international collating order.

dbSortPDXNor	Paradox Norwegian and Danish collating order.

dbSortPDXSwe	Paradox Swedish and Finnish collating order.

dbSortPolish	Polish collating order.

dbSortSpanish	Spanish collating order.

dbSortSwedFin	Swedish and Finnish collating order.

dbSortTurkish	Turkish collating order.

dbSortUndefined	Collating order undefined or unknown.

EditMode Property Constants (All are [image])

Constant	Description

dbEditNone	No editing operation in effect.

dbEditInProgress	Edit method invoked.

dbEditAdd	AddNew method invoked.

Permissions Property Constants

Container.Permissions Property (All are [image])

Constant	Description

dbSecNoAccess	No access to the object.

dbSecFullAccess	Has full access to the object.

dbSecDelete 	Can delete the object.

dbSecReadSec 	Can read the object's security-related information.

dbSecWriteSec 	Can alter access permissions.

dbSecWriteOwner 	Can change the Owner property setting.

Databases Container.Permissions Property (All are [image])

Constant	Description

dbSecDBAdmin	Gives user permission to make a database replicable and change the database password.

dbSecDBCreate	Can create new databases (valid only on the databases Container object in the system database).

dbSecDBOpen	Can open the database.

dbSecDBExclusive	Has exclusive access.

Tables Container.Permissions Property (All are [image])

Constant	Description

dbSecCreate	Create new tables (valid only with a Container object that represents a table or with the databases Container object in the system database).

dbSecReadDef	Read the table definition, including column and index information.

dbSecWriteDef	Modify or delete table definition, including column and index information.

dbSecRetrieveData 	Retrieve data from the document.

dbSecInsertData	Add records.

dbSecReplaceData	Modify records.

dbSecDeleteData	Delete records.

Document.Permissions Property (All are [image])

Constant	Description

dbSecCreate	Create new tables (valid only with a Container object that represents a table).

dbSecDBCreate	Can create new databases (valid only on the databases Container object in the system database).

dbSecDelete 	Can delete the object.

dbSecDBOpen	Can open the database.

dbSecDBExclusive	Has exclusive access.

dbSecDelete 	Can delete the object.

dbSecDeleteData	Delete records.

dbSecFullAccess	Has full access to the object.

dbSecInsertData	No access to the object.

dbSecReadDef	Read the table definition, including column and index information.

dbSecReadSec 	Can read the object's security-related information.

dbSecReplaceData	Modify records.

dbSecRetrieveData 	Retrieve data from the document.

dbSecWriteDef	Modify or delete table definition, including column and index information.

dbSecWriteSec 	Can alter access permissions.

dbSecWriteOwner 	Can change the Owner property setting.

Type Property Constants

Field.Type Property (All are [image])
Parameter.Type Property (All are [image])
Property.Type Property (All are [image])

Constant	Description

dbBoolean	Boolean (True/False) data.

dbByte	Byte (8-bit) data.

dbInteger	Integer data.

dbLong	Long Integer data.

dbCurrency	Currency data.

dbSingle	Single-precision floating-point data.

dbDouble	Double-precision floating-point data.

dbDate	Date value data.

dbText	Text data (variable width).

dbLongBinary	Binary data (bitmap).

dbMemo	Memo data (extended text).

dbGUID	GUID data.

QueryDef.Type Property (All are [image])

Constant	Description

dbQSelect	SELECT query.

dbQAction	Action query.

dbQCrosstab	Crosstab query.

dbQDelete	DELETE query.

dbQUpdate	UPDATE query.

dbQAppend	APPEND query.

dbQMakeTable	Make-table query.

dbQDDL	Data definition language (DDL) query.

dbQSQLPassThrough	SQL pass-through query.

dbQSetOperation	Set operation query.

dbQSPTBulk	Bulk operation query.

Recordset.Type Property (All are [image])

Constants	Description

dbOpenTable 	Open table-type Recordset.

dbOpenDynaset 	Open dynaset-type Recordset.

dbOpenSnapshot	Open snapshot-type Recordset.

CompactDatabase, CreateDatabase Methods locale Argument Constants (All are [image])

Constant	Description

dbLangArabic	Arabic collating order.

dbLangCzech	Czech collating order.

dbLangDutch	Dutch collating order.

dbLangGeneral	English, German, French, Portuguese, Italian, and Modern Spanish collating order.

dbLangGreek	Greek collating order.

dbLangHebrew	Hebrew collating order.

dbLangHungarian	Hungarian collating order.

dbLangIcelandic	Icelandic collating order.

dbLangJapanese	Japanese collating order.

dbLangNeutral	Neutral collating order.

dbLangNordic	Nordic collating order.

dbLangNorwdan	Norwegian and Danish collating order.

dbLangPolish	Polish collating order.

dbLangCyrillic	Russian collating order.

dbLangSpanish	Spanish collating order.

dbLangSwedfin	Swedish and Finnish collating order.

dbLangTurkish	Turkish collating order.

CompactDatabase Method options Argument Constants (All are [image])

Constant	Description

dbDecrypt	Decrypt database while compacting.

dbEncrypt	Encrypt database.

dbVersion10	Microsoft Jet database engine version 1.0.

dbVersion11	Microsoft Jet database engine version 1.1.

dbVersion20	Microsoft Jet database engine version 2.0.

dbVersion30	Microsoft Jet database engine version 3.0.

CreateDatabase Method options Argument Constants (All are [image])

Constant	Description

dbEncrypt	Encrypt database.

dbVersion10	Microsoft Jet database engine version 1.0.

dbVersion11	Microsoft Jet database engine version 1.1.

dbVersion20	Microsoft Jet database engine version 2.0.

dbVersion30	Microsoft Jet database engine version 3.0.

Execute Method options Argument Constants (All are [image])

Constant	Description

dbDenyWrite	Deny write permission to other users.

dbInconsistent	Inconsistent updates.

dbConsistent	Consistent updates.

dbSQLPassThrough	SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.

dbFailOnError	Rolls back updates if an error occurs.

dbSeeChanges	Generates a run-time error if another user is changing data you are editing.

Idle Method Optional Argument Constant (This is [image])

Constant	Description

dbFreeLocks	Delay processing until all read locks are released.

OpenRecordset Method type Argument Constants (All are [image])

Constants	Description

dbOpenTable 	Open table-type Recordset.

dbOpenDynaset 	Open dynaset-type Recordset.

dbOpenSnapshot	Open snapshot-type Recordset.

OpenRecordset Method options Argument Constants (All are [image])

Constant	Description

dbDenyWrite	Other users can't change Recordset records.

dbDenyRead	Other users can't read Recordset records.

dbReadOnly	Open the Recordset as read-only.

dbAppendOnly	You can add new records to the dynaset, but you can't read existing records.

dbInconsistent	Updates apply to all dynaset fields, even if other records are affected.

dbConsistent	Updates apply only to those fields that will not affect other records in the dynaset.

dbSQLPassThrough	Sends an SQL statement to an ODBC database.

dbForwardOnly	Create a forward-only scrolling snapshot-type Recordset.

MakeReplica Method Optional Argument Constant (This is [image])

Constant	Description

dbRepMakeReadOnly	Replicable elements of new database are read-only.

Synchronize Method exchange Argument Constants (All are [image])

Constant	Description

dbRepExportChanges	Send changes from current database to target database.

dbRepImportChanges	Receive changes from target database.

dbRepImpExpChanges	Bidirectional exchange.


Container Object, Containers Collection, and Document Object, Documents Collection Example

This example enumerates the properties of all the Container and Document objects in the current database. See the properties listed in the Container and Document summary topics for additional examples.

Function EnumerateDocuments () As Integer

Dim dbsCurrent As Database

Dim conTest As Container, docTest As Document

Dim intC As Integer, intD As Integer

Set dbsCurrent = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

For intC = 0 To dbsCurrent.Containers.Count - 1

Set conTest = dbsCurrent.Containers(intC)

Debug.Print ">> Container: "; conTest.Name;

Debug.Print "  Owner: "; conTest.Owner

Debug.Print "  UserName: "; conTest.UserName;

Debug.Print "  Permissions: "; conTest.Permissions

Debug.Print

For intD = 0 To conTest.Documents.Count - 1

Set docTest = conTest.Documents(intD)

Debug.Print " > Document: "; docTest.Name;

Debug.Print "  Owner: "; docTest.Owner;

Debug.Print "  Container: "; docTest.Container

Debug.Print "  UserName: "; docTest.UserName;

Debug.Print "  Permissions: "; docTest.Permissions

Debug.Print "  DateCreated: "; docTest.DateCreated;

Debug.Print "  LastUpdated: "; docTest.LastUpdated

Debug.Print

Next intD

Next intC

EnumerateDocuments = True

End Function


Database Object, Databases Collection Example

This example creates a new Database object and opens it (thereby appending it to the Databases collection) in the default Workspace object. Then it enumerates all the collections contained by each Database object and the properties of the new Database object and closes the new Database. See the methods and properties listed in the Database summary topic for additional examples.

Function EnumerateDatabase () As Integer

Dim wrkDefault As Workspace

Dim dbsEnum As Database, dbsTemp As Database

Dim intOBJ As Integer, intDB As Integer

Set wrkDefault = Workspaces(0)

Set dbsEnum = wrkDefault.CreateDatabase("Northwind.mdb", dbLangGeneral)

' Enumerate all open databases.

For intDB = 0 To wrkDefault.Databases.Count - 1

Set dbsTemp = wrkDefault.Databases(intDB)

Debug.Print

Debug.Print "Enumeration of Databases: "; dbsTemp.Name

Debug.Print

' Enumerate containers.

Debug.Print "Container: Name, Owner"

For intOBJ = 0 To dbsTemp.Containers.Count - 1

Debug.Print "  "; dbsTemp.Containers(intOBJ).Name;

Debug.Print ", "; dbsTemp.Containers(intOBJ).Owner

Next intOBJ

Debug.Print

' Enumerate query definitions.

Debug.Print "QueryDef: Name"

For intOBJ = 0 To dbsTemp.QueryDefs.Count - 1

Debug.Print "  "; dbsTemp.QueryDefs(intOBJ).Name

Next intOBJ

Debug.Print

' Enumerate Recordsets.

' No output because no Recordset is open.

Debug.Print "Recordset: Name"

For intOBJ = 0 To dbsTemp.Recordsets.Count - 1

Debug.Print "  "; dbsTemp.Recordsets(intOBJ).Name

Next intOBJ

Debug.Print

' Enumerate relationships.

Debug.Print "Relation: Name, Table, ForeignTable"

For intOBJ = 0 To dbsTemp.Relations.Count - 1

Debug.Print "  "; dbsTemp.Relations(intOBJ).Name;

Debug.Print ", "; dbsTemp.Relations(intOBJ).Table;

Debug.Print ", "; dbsTemp.Relations(intOBJ).ForeignTable

Next intOBJ

Debug.Print

' Enumerate table definitions.

Debug.Print "TableDef: Name, DateCreated"

For intOBJ = 0 To dbsTemp.TableDefs.Count - 1

Debug.Print "  "; dbsTemp.TableDefs(intOBJ).Name;

Debug.Print ", "; dbsTemp.TableDefs(intOBJ).DateCreated

Next intOBJ

Debug.Print

Next intDB

' Enumerate built-in properties of dbsEnum.

Debug.Print " dbsEnum.Name: "; dbsEnum.Name

Debug.Print " dbsEnum.CollatingOrder: "; dbsEnum.CollatingOrder

Debug.Print " dbsEnum.Connect: "; dbsEnum.Connect

Debug.Print " dbsEnum.QueryTimeout: "; dbsEnum.QueryTimeout

Debug.Print " dbsEnum.Transactions: "; dbsEnum.Transactions

Debug.Print " dbsEnum.Updatable: "; dbsEnum.Updatable

Debug.Print

dbsEnum.Close	' File remains on disk.

EnumerateDatabase = True

End Function


DBEngine Object Example

This example enumerates the collections of the DBEngine object. See the methods and properties of DBEngine for additional examples.

Function EnumerateDBEngine () As Integer

Dim wrkEnum As Workspace, intWSP As Integer

Debug.Print "Enumeration of DBEngine"

Debug.Print

' Enumerate all workspaces.

Debug.Print "Workspaces: Name, UserName"

For intWSP = 0 To Workspaces.Count - 1

Set wrkEnum = Workspaces(intWSP)

Debug.Print "  "; wrkEnum.Name;

Debug.Print ", "; wrkEnum.UserName

Next intWSP

Debug.Print

' Enumerate built-in properties.

Debug.Print "DBEngine.Version: "; DBEngine.Version

Debug.Print "DBEngine.LoginTimeout: "; DBEngine.LoginTimeout

EnumerateDBEngine = True

End Function


Dynaset-Type Recordset Example

This example creates a new dynaset-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then edits the record(s).

Function ChangeSQL () As Integer

Dim dbsBiblio As Database, rstTitles As Recordset

Dim strSelect As String

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

strSelect = "Select * From Titles Where Title = 'Using SQL' "

Set rstTitles = dbsBiblio.OpenRecordset(strSelect, dbOpenDynaset)

If rstTitles.RecordCount > 0 and rstTitles.Updatable Then

Do Until rstTitles.EOF

With rstTitles

.Edit

![Year Published] = 1994	' Change year published.

.Update

.MoveNext

End With

Loop

Else

Debug.Print "No such title or table not updatable"

End If

dbsBiblio.Close

ChangeSQL = True

End Function


Field Object, Fields Collection Example

This example creates a TableDef object and a Field object, appends the Field to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the current database. The example enumerates all the fields in the new TableDef object and all the properties of the new Field. See the methods and properties listed in the Field summary topic for additional examples.

Function EnumerateField () As Integer

Dim dbsNorthwind As Database

Dim tdfTest As TableDef

Dim fldTest As Field

Dim I As Integer

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfTest = dbsNorthwind.CreateTableDef("MyTable")

Set fldTest = tdfTest.CreateField("MyField", dbDate)

tdfTest.Fields.Append fldTest

dbsNorthwind.TableDefs.Append tdfTest

' Get database name.

Debug.Print

Debug.Print "Database Name: "; dbsNorthwind.Name

Debug.Print

' Enumerate all fields in tdfTest.

Debug.Print "TableDefs: Name; Fields: Name"

For I = 0 To tdfTest.Fields.Count - 1

Debug.Print "  "; tdfTest.Name;

Debug.Print "; "; tdfTest.Fields(I).Name

Next I

Debug.Print

' Enumerate built-in properties of fldTest.

Debug.Print "fldTest.Name: "; fldTest.Name

Debug.Print "AllowZeroLength: "; fldTest.AllowZeroLength

Debug.Print "Attributes: "; fldTest.Attributes

Debug.Print "CollatingOrder: "; fldTest.CollatingOrder

Debug.Print "DefaultValue: "; fldTest.DefaultValue

Debug.Print "OrdinalPosition: "; fldTest.OrdinalPosition

Debug.Print "Required: "; fldTest.Required

Debug.Print "Size: "; fldTest.Size

Debug.Print "SourceField: "; fldTest.SourceField

Debug.Print "SourceTable: "; fldTest.SourceTable

Debug.Print "Type: "; fldTest.Type

Debug.Print "ValidationRule: "; fldTest.ValidationRule

Debug.Print "ValidationText: "; fldTest.ValidationText

EnumerateField = True

End Function


Group Object, Groups Collection and User Object, Users Collection Example

This example illustrates the use of the Group and User objects and the Groups and Users collections. First, it creates a new User object with the Name, PID, and Password property settings of "Pat Smith", "abc123DEF456", and "My Secret" and appends the object to the Users collection of the default Workspace object. Next, it creates a new Group object with the Name and PID property settings of "Accounting" and "UVW987xyz654" and appends the object to the Groups collection of the default Workspace object. Then the example adds user Pat Smith to the Accounting group. Finally, it enumerates the User and Group objects in the collections of the default Workspace object. See the methods and properties listed in the Group and User summary topics for additional examples.

Function EnumerateUserGroup () As Integer

Dim wrkDefault As Workspace

Dim usrPatSmith As User, usrTemp As User, usrGroupUser As User

Dim grpAccount As Group, grpTemp As Group, grpMember As Group

Dim intI As Integer, intJ As Integer

Set wrkDefault = DBEngine.Workspaces(0)

' Create and append new user.

Set usrPatSmith = wrkDefault.CreateUser("Pat Smith", _
"abc123DEF456", "My Secret")

wrkDefault.Users.Append usrPatSmith

' Create and append new group.

Set grpAccount = wrkDefault.CreateGroup("Accounting", _
"UVW987xyz654")

wrkDefault.Groups.Append grpAccount

' Add new user to new group or converse; do one or the other, not both.

' Use Refresh because both collections are referred to in following

' code.

'	wrkDefault.Groups![Accounting].Users.Append usrGroupUser

'	wrkDefault.Users![Pat Smith].Groups.Refresh

' Or add group to user and refresh group.

' Create new group object for user Pat Smith

Set grpMember = usrPatSmith.CreateGroup("Accounting")

'  wrkDefault.Users![Pat Smith].Groups.Append grpMember

'  wrkDefault.Groups![Accounting].Users.Refresh

' Enumerate all users.

For intJ = 0 To wrkDefault.Users.Count - 1

Set usrTemp = wrkDefault.Users(intJ)

Debug.Print

Debug.Print "Enumeration of Users: "; usrTemp.Name

Debug.Print

' Enumerate groups.

Debug.Print "	Groups: "

For intI = 0 To usrTemp.Groups.Count - 1

Debug.Print "	"; usrTemp.Groups(intI).Name

Next intI

Next intJ

' Enumerate all groups.

Debug.Print "------------------------------------"

For intJ = 0 To wrkDefault.Groups.Count - 1

Set grpTemp = wrkDefault.Groups(intJ)

Debug.Print

Debug.Print "Enumeration of Groups: "; grpTemp.Name

Debug.Print

' Enumerate users.

Debug.Print "	Users: "

For intI = 0 To grpTemp.Users.Count - 1

Debug.Print "	"; grpTemp.Users(intI).Name

Next intI

Next intJ

EnumerateUserGroup = True

End Function


Index Object, Indexes Collection Example

This example creates a new TableDef object and two new Field objects, appends the Field objects to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the database. Then it creates a new primary Index object, includes the two Field objects in it, and appends the Index to the Indexes collection of the TableDef. Finally, the example enumerates the Index objects in the current database. See the methods and properties listed in the Index summary topic for additional examples.

Function EnumerateIndex () As Integer

Dim  dbsDefault As Database, tdfTest As TableDef

Dim fldOne As Field, fldTwo As Field, idxPrimary As Index

Dim I As Integer

' Get workspace and database.

Set dbsDefault = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")	' Create table with two fields.

Set tdfTest = dbsDefault.CreateTableDef("MyTable")

Set fldOne = tdfTest.CreateField("Field1", dbLong)

fldOne.Required = True	' No Null values allowed.

tdfTest.Fields.Append fldOne

Set fldTwo = tdfTest.CreateField("Field2", dbLong)

fldTwo.Required = True	' No Null values allowed.

tdfTest.Fields.Append fldTwo

dbsDefault.TableDefs.Append tdfTest

' Create primary index for those two fields.

Set idxPrimary = tdfTest.CreateIndex("MyIndex")

idxPrimary.Primary = True

Set fldOne = tdfTest.CreateField("Field1")

idxPrimary.Fields.Append fldOne

Set fldTwo = tdfTest.CreateField("Field2")

idxPrimary.Fields.Append fldTwo

tdfTest.Indexes.Append idxPrimary

' Enumerate index and its fields.

Debug.Print "Index: "; idxPrimary.Name

Debug.Print "  Required: "; idxPrimary.Required

Debug.Print "  IgnoreNulls: "; idxPrimary.IgnoreNulls

Debug.Print "  Primary: "; idxPrimary.Primary

Debug.Print "  Clustered: "; idxPrimary.Clustered

Debug.Print "  Unique: "; idxPrimary.Unique

Debug. Print "  Foreign: "; idxPrimary.Foreign

Debug.Print

Debug.Print "Fields in Index: ";

For I = 0 To idxPrimary.Fields.Count - 1

Debug.Print " "; idxPrimary.Fields(I).Name;

Next I

Debug.Print

EnumerateIndex = True

End Function

This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

Dim dbsDefault As Database

Dim rstTitles as Recordset

' Get workspace and database.

Set dbsDefault = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstTitles = dbsDefault.OpenRecordset("Titles")

rstTitles.Index = "MyIndex"

.

.

.


Parameter Object, Parameters Collection Example

This example sets two query parameters for a hypothetical parameter query named “ParamQuery,” executes the query by opening a Recordset from the QueryDef, and then prints the properties of each parameter. Note that this query does not actually exist in the Northwind sample database. The parameter data types are of type Date. See the methods and properties listed in the Parameter summary topic for additional examples.

Dim dbsCurrent As Database

Dim qdfParam As QueryDef, prmEnum As Parameter

Dim rstParam As Recordset

Dim X As Integer

Set dbsCurrent = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set qdfParam = dbsCurrent.QueryDefs("ParamQuery")	' Open existing
' QueryDef.

qdfParam.Parameters("Order Date") = "10/11/94"	' Set parameters.

qdfParam.Parameters("Ship Date") = "11/4/94"

Set rstParam = qdfParam.OpenRecordset()	' Open Recordset.

For X = 0 To qdfParam.Parameters.Count - 1

Set prmEnum = qdfParam.Parameters(X)

Debug.Print prmEnum.Name	' Print parameter properties.

Debug.Print prmEnum.Type

Debug.Print prmEnum.Value

Next X

rstParam.Close


Property Object, Properties Collection Example

This example creates a user-defined property for the current database, sets its Type and Value properties, and appends it to the Properties collection of the database. Then the example enumerates all properties in the database. See the properties listed in the Property summary topic for additional examples.

Function EnumerateProperty () As Integer

Dim wrkDefault As Workspace, dbsExample As Database

Dim prpUserDefined As Property, prpEnum As Property

Dim I As Integer

' Get default workspace and current database.

Set wrkDefault = DBEngine.Workspaces(0)

Set dbsExample = wrkDefault.OpenDatabase("Northwind.mdb")

' Create user-defined property.

Set prpUserDefined = dbsExample.CreateProperty()

' Set properties of new property.

prpUserDefined.Name = "UserDefinedProperty"

prpUserDefined.Type = dbText

prpUserDefined.Value = "This is a user-defined property."

' Append property to current database.

dbsExample.Properties.Append prpUserDefined

' Enumerate all properties of current database.

Debug.Print "Properties of Database "; dbsExample.Name

For I = 0 To dbsExample.Properties.Count - 1

Set prpEnum = dbsExample.Properties(I)

Debug.Print

Debug.Print " Properties("; I; ")"

Debug.Print "  Name: "; prpEnum.Name

Debug.Print "  Type: "; prpEnum.Type

Debug.Print "  Value: "; prpEnum.Value

Debug.Print "  Inherited: "; prpEnum.Inherited

Next I

Debug.Print

EnumerateProperty = True

End Function

This example shows how you can set an application-defined property (or any user-defined property that may not yet exist) without causing a run-time error. The example sets an arbitrary property of a Field object. The return value of the function is True if the value was properly set. The return value is False if an unexpected error occurs when the property is set. See the properties listed in the Property summary topic for additional examples.

Function SetFieldProperty (fldPropVal As Field, strName As String, intType As Integer, varValue As Variant) As Integer

Const ERR_PROPERTY_NONEXISTENT = 3270

Dim prpUserDefined As Property

On Error Resume Next	' Function handles errors.

SetFieldProperty = True

fldPropVal.Properties(strName) = varValue

If Err <> 0 Then	' Error occurred when value was set.

If Err <> ERR_PROPERTY_NONEXISTENT

On Error GoTo 0

SetFieldProperty = False

Else

' Create Property object, setting its Name, Type, and Value properties.

On Error Resume Next

Set prpUserDefined = fldPropVal.CreateProperty(strName, intType, varValue)

fldPropVal.Properties.Append prpUserDefined

If Err <> 0 Then

SetFieldProperty = False

End If

On Error GoTo 0

End If

End If

End Function


QueryDef Object, QueryDefs Collection Example

This example creates a new QueryDef object and appends it to the QueryDefs collection in the current database. Then the example enumerates all the QueryDef objects in the database and all the properties of the new QueryDef. See the methods and properties listed in the QueryDef summary topic for additional examples.

Function EnumerateQueryDef () As Integer

Dim wrkCurrent As Workspace, dbsExample As Database, qdfTest As QueryDef

Dim I As Integer

Set wrkCurrent = DBEngine.Workspaces(0)

Set dbsExample = wrkCurrent.OpenDatabase("Northwind.mdb")

Set qdfTest = dbsExample.CreateQueryDef("This is a test")

Debug.Print

' Enumerate QueryDef objects.

Debug.Print

For I = 0 To dbsExample.QueryDefs.Count - 1

Debug.Print dbsExample.QueryDefs(I).Name

Next I

' Enumerate built-in properties of qdfTest.

Debug.Print

Debug.Print "qdfTest.Name: "; qdfTest.Name

Debug.Print "qdfTest.DateCreated: "; qdfTest.DateCreated

Debug.Print "qdfTest.LastUpdated: "; qdfTest.LastUpdated

Debug.Print "qdfTest.SQL: "; qdfTest.SQL

Debug.Print "qdfTest.ODBCTimeout: "; qdfTest.ODBCTimeout

Debug.Print "qdfTest.Updatable: "; qdfTest.Updatable

Debug.Print "qdfTest.Type: "; qdfTest.Type

Debug.Print "qdfTest.Connect: "; qdfTest.Connect

Debug.Print "qdfTest.ReturnsRecords: "; qdfTest.ReturnsRecords

dbsExample.QueryDefs.Delete "This is a test"

EnumerateQueryDef = True

End Function


Recordset Object, Recordsets Collection Example

This example creates a new Recordset object and opens it (thereby appending it to the Recordsets collection) in the default database. Then the example enumerates all the Recordset objects in the current database and all the fields in each Recordset object and closes the new Recordset. See the methods and properties in the Recordset summary topic for additional examples.

Function EnumerateRecordset () As Integer

Dim dbsExample As Database, rstOrders As Recordset
Dim rstTemp As Recordset

Dim I As Integer, J As Integer

Set dbsExample = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstOrders = dbsExample.OpenRecordset("Orders", dbOpenSnapshot)

Debug.Print

' Enumerate all Recordset objects.

For J = 0 To dbsExample.Recordsets.Count - 1

Set rstTemp = dbsExample.Recordsets(J)

Debug.Print

Debug.Print "Enumeration of Recordset objects("; J; "): "; rstTemp.Name

Debug.Print

' Enumerate fields.

Debug.Print "Fields: Name, Type, Value"

For I = 0 To rstTemp.Fields.Count - 1

Debug.Print "  "; rstTemp.Fields(I).Name;

Debug.Print ", "; rstTemp.Fields(I).Type;

If rstTemp.Fields(I).Type = dbText Then

Debug.Print ", "; rstTemp.Fields(I).Value

End if

Next I

Next J

dbsExample.Close

EnumerateRecordset = True

End Function


Relation Object, Relations Collection Example

This example creates a one-to-many relationship between single fields in two tables. Because referential integrity is enforced for the relationship, an index is created for the primary table. See the methods and properties listed in the Relation summary topic for additional examples.

Function EnumerateRelation () As Integer

Dim dbsExample As Database

Dim tdfReferenced As TableDef, tdfReferencing As TableDef
Dim fldPrimeKey As Field, idxUnique As Index, relEnforced As Relation

Dim I As Integer

' Get database.

Set dbsExample = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create referenced table with primary key.

Set tdfReferenced = dbsExample.CreateTableDef("Referenced")

Set fldPrimeKey = tdfReferenced.CreateField("PrimaryKey", dbLong)

tdfReferenced.Fields.Append fldPrimeKey

' Create unique index for enforced referential integrity.

Set idxUnique = tdfReferenced.CreateIndex("UniqueIndex")

idxUnique.Primary = True ' No Null values allowed.

Set fldPrimeKey = tdfReferenced.CreateField("PrimaryKey")

idxUnique.Fields.Append fldPrimeKey

tdfReferenced.Indexes.Append idxUnique

dbsExample.TableDefs.Append tdfReferenced

' Create referencing table with foreign key.

Set tdfReferencing = dbsExample.CreateTableDef("Referencing")

Set fldPrimeKey = tdfReferencing.CreateField("ForeignKey", dbLong)

tdfReferencing.Fields.Append fldPrimeKey

dbsExample.TableDefs.Append tdfReferencing

' Create one-to-many relationship and enforce referential integrity.

Set relEnforced = dbsExample.CreateRelation("EnforcedOneToMany")

relEnforced.Table = "Referenced"

relEnforced.ForeignTable = "Referencing"

' Don't set either dbRelationUnique or dbRelationDontEnforce.

relEnforced.Attributes = 0

Set fldPrimeKey = relEnforced.CreateField("PrimaryKey")

fldPrimeKey.ForeignName = "ForeignKey"

relEnforced.Fields.Append fldPrimeKey

dbsExample.Relations.Append relEnforced

' Enumerate relation and its fields.

Debug.Print "Relation: "; relEnforced.Name

Debug.Print "  Primary Table: "; relEnforced.Table

Debug.Print "  Foreign Table: "; relEnforced.ForeignTable

Debug.Print "  Attributes: "; relEnforced.Attributes

Debug.Print "Fields in Relation: Primary, Foreign";

For I = 0 To relEnforced.Fields.Count - 1

Set fldPrimeKey = relEnforced.Fields(I)

Debug.Print "  "; fldPrimeKey.Name;

Debug.Print ", "; fldPrimeKey.ForeignName

Next I

Debug.Print

dbsExample.Relations.Delete "EnforcedOneToMany"

dbsExample.TableDefs.Delete "Referenced"

dbsExample.TableDefs.Delete "Referencing"

EnumerateRelation = True

End Function


Snapshot-Type Recordset Example

This example creates a new snapshot-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then finds a record and prints it.

Function ShowVBSQL () As Integer

Dim dbsPublish As Database, rstTitles As Recordset

Dim I As Integer, J As Integer

Set dbsPublish = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set rstTitles = dbsPublish.OpenRecordset("Titles", dbOpenSnapshot)

If rstTitles.RecordCount > 0 Then

rstTitles.FindFirst "Title Like '*VBSQL*'"  ' Any title on VBSQL

Do until rstTitles.NoMatch = True

Debug.Print rstTitles!Title

rstTitles.FindNext "Title Like '*VBSQL*'"

Loop

Else

Debug.Print "No such title"

End If

dbsPublish.Close

ShowVBSQL = True

End Function


Table-Type Recordset Example

This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

Dim dbsExample As Database

Dim rstTitles as Recordset

' Get workspace and database.

Set dbsExample = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set rstTitles = dbsExample.OpenRecordset("Titles", dbOpenTable)

rstTitles.Index = "MyIndex"

...

...

...


TableDef Object, TableDefs Collection Example

This example creates a new TableDef object, adds a Field object to it, and appends the TableDef to the TableDefs collection in the current database. Then the example enumerates all the TableDef objects in the current database and all the properties of the new TableDef. See the methods and properties listed in the TableDef summary topic for additional examples.

Function EnumerateTableDef () As Integer

Dim dbsExample As Database

Dim tdfEnum As TableDef

Dim fldDate As Field

Dim I As Integer

Set dbsExample = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfEnum = dbsExample.CreateTableDef("MyTable")

Set fldDate = tdfEnum.CreateField("Date", dbDate)

tdfEnum.Fields.Append fldDate

dbsExample.TableDefs.Append tdfEnum

' Get database name.

Debug.Print "Database Name: "; dbsExample.Name

' Enumerate all fields in tdfEnum.

Debug.Print "TableDef: Name; Field: Name"

For I = 0 To tdfEnum.Fields.Count - 1

Debug.Print "  "; tdfEnum.Name;

Debug.Print "; "; tdfEnum.Fields(I).Name

Next I

Debug.Print

' Enumerate all indexes in tdfEnum.

Debug.Print "TableDef: Name; Index: Name"

For I = 0 To tdfEnum.Indexes.Count - 1

Debug.Print "  "; tdfEnum.Name;

Debug.Print "; "; tdfEnum.Indexes(I).Name

Next I

Debug.Print

' Enumerate built-in properties of tdfEnum.

Debug.Print "tdfEnum.Name: "; tdfEnum.Name

Debug.Print "tdfEnum.Attributes: "; tdfEnum.Attributes

Debug.Print "tdfEnum.Connect: "; tdfEnum.Connect

Debug.Print "tdfEnum.DateCreated: "; tdfEnum.DateCreated

Debug.Print "tdfEnum.LastUpdated: "; tdfEnum.LastUpdated

Debug.Print "tdfEnum.RecordCount: "; tdfEnum.RecordCount

Debug.Print "tdfEnum.SourceTableName: "; tdfEnum.SourceTableName

Debug.Print "tdfEnum.Updatable: "; tdfEnum.Updatable

Debug.Print "tdfEnum.ValidationRule: "; tdfEnum.ValidationRule

Debug.Print "tdfEnum.ValidationText: "; tdfEnum.ValidationText

EnumerateTableDef = True

End Function


Workspace Object, Workspaces Collection Example

This example creates a new Workspace and appends it to the Workspaces collection. It assumes that the user JustAUser with a password of Secret has already been created. The example enumerates the collections of each Workspace object and finally closes the new Workspace. See the methods and properties of the Workspace object or Workspaces collection for additional examples.

Function EnumerateWorkspace () As Integer

Dim wrkEnum As Workspace, wrkNew As Workspace

Dim I As Integer, J As Integer

' Create new workspace and add it to collection.

Set wrkNew = DBEngine.CreateWorkspace("NewWorkspace", "JustAUser", _
"")

DBEngine.Workspaces.Append wrkNew

' Enumerate all workspaces.

For J = 0 To DBEngine.Workspaces.Count - 1

Set wrkEnum = DBEngine.Workspaces(J)

Debug.Print

Debug.Print "Enumeration of Workspaces("; J; "): "; wrkEnum.Name

Debug.Print

' Enumerate databases.

Debug.Print "Databases: Name"

For I = 0 To wrkEnum.Databases.Count - 1

Debug.Print "  "; wrkEnum.Databases(I).Name

Next I

' Enumerate all user accounts.

Debug.Print "Users: Name"

For I = 0 To wrkEnum.Users.Count - 1

Debug.Print "  "; wrkEnum.Users(I).Name

Next I

Debug.Print

' Enumerate all group accounts.

Debug.Print "Groups: Name"

For I = 0 To wrkEnum.Groups.Count - 1

Debug.Print "  "; wrkEnum.Groups(I).Name

Next I

Debug.Print

Next J

Debug.Print

' Enumerate built-in properties of wrkNew.

Debug.Print "wrkNew.Name: "; wrkNew.Name

Debug.Print "wrkNew.UserName: "; wrkNew.UserName

Debug.Print

wrkNew.Close

EnumerateWorkspace = True

End Function


AddNew Method, LastModified Property Example

This example creates a new record in a table named Customers, enters values, saves the changes, and then moves to and deletes the new record.

Dim dbsNorthwind As Database, rstCustomers As Recordset

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Open table.

Set rstCustomers = dbsNorthwind.OpenRecordset("Customers")

With rstCustomers

.AddNew	' Create new record.

!CustomerID = "FINNF"	' Set record key.

!CompanyName = "Finnegan's Foods"	' Set company name.

.Update	' Save changes.

.Bookmark = rstCustomers.LastModified	' Go to new record

.Delete	' Delete new record.

.Close	' Close Table.

End With

dbsNorthwind.Close	' Close Database.


Append Method Example

The example defines a new field and appends it to a Fields collection.

Dim dbsBiblio As Database, fldPhone As Field, tdfAuthors As TableDef

' Open a database.

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set tdfAuthors = dbsBiblio.TableDefs("Authors")

Set fldPhone = dbsBiblio.CreateField()

fldPhone.Name = "Phone"	' Set field properties.

fldPhone.Type = dbText

fldPhone.Size = 15

' Append field to collection.

dbsBiblio.tdfAuthors.Fields.Append fldPhone

dbsBiblio.tdfAuthors.Fields.Delete "Phone"

dbsBiblio.Close


 AppendChunk, FieldSize, GetChunk Methods Example

This example uses the GetChunk method to return consecutive 16K chunks of the Notes field in the Employees table of the database Northwind.mdb. It uses FieldSize to determine how many chunks it needs to copy and then copies the chunks to the string array NoteArray() where they can be changed. It then uses AppendChunk to copy NoteArray() back to Notes.

' This line should be in Declarations section.

Option Base 1

Sub GetNotes

Const ChunkSize = 16384	' Set size of chunk.

Dim intChunks As Integer, lngTotalSize As Long, intX As Integer

Dim dbsNorthwind As Database, rstEmployees As Recordset

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Open table.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")

' Get field size.

lngTotalSize = rstEmployees![Notes].FieldSize()

' How many chunks?

intChunks = lngTotalSize\ChunkSize - (lngTotalSize Mod ChunkSize _
<> 0)

ReDim NoteArray(intChunks) As String * ChunkSize

' Get current Notes field.

For intX = 1 To intChunks

NoteArray(intX) = rstEmployees![Notes].GetChunk((intX - 1) * _

ChunkSize, ChunkSize)

Next intX

...	' Make changes.

rstEmployees.Edit	' Enable editing.

rstEmployees!Notes = ""	' Initialize Notes field.

For intX = 1 To intChunks

' Replace with edited Notes.

rstEmployees![Notes].AppendChunk NoteArray(intX)

Next intX

rstEmployees.Update	' Save changes.

rstEmployees.Close

dbsNorthwind.Close 	' Close database.

End Sub


BeginTrans, CommitTrans, Rollback Methods Example

This example changes the job title of all sales representatives in the Employees table of the database. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved using the Update method.

One or more table pages remain locked while the user decides whether or not to accept the changes. For this reason, this technique isn't recommended but shown only as an example.

Sub ChangeTitle

Dim strName As String, strMessage As String, strPrompt As String

Dim wspDefault As Workspace, dbsNorthwind As Database

Dim rstEmployees As Recordset

strPrompt = "Change title to Account Executive?"

Set wspDefault = DBEngine.Workspaces(0)   ' Get default Workspace.

' Get current database.

Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")

' Open table.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenTable)

wspDefault.BeginTrans	' Start of transaction.

rstEmployees.MoveFirst

Do Until rstEmployees.EOF

If rstEmployees![Title] = "Sales Representative" Then

strName = rstEmployees![LastName] & ", " & _

rstEmployees![FirstName]

strMessage = "Employee: " & strName & vbCrLf & vbCrLf

If MsgBox(strMessage & Prompt, vbQuestion + vbYesNo, _

"Change Job Title") = YES Then

rstEmployees.Edit	' Enable editing.

rstEmployees![Title] = "Account Executive"

rstEmployees.Update	' Save changes.

End If

End If

rstEmployees.MoveNext	' Move to next record.

Loop

If MsgBox("Save all changes?", vbQuestion + vbYesNo, _

" Save Changes") = YES Then

wspDefault.CommitTrans	' Commit changes.

Else

wspDefault.Rollback	' Undo changes.

End If

rstEmployees.Close	' Close table.

dbsNorthwind.Close

End Sub


Clone Method Example

This example creates a Recordset object based on the Orders table in the Northwind database and uses the Clone method to create a second Recordset object. Each Recordset object has its own current record that can be moved independently of the other. A bookmark is used to initially make the same record current in both Recordset objects.

Dim dbsNorthwind As DatabaseDim rstOriginal As Recordset, rstDuplicate As RecordsetDim strPosition As String

Set dbsNorthwind = DBEngine.Workspaces(0).Databases(“Northwind.mdb”)

' Create first Recordset.

Set rstOriginal = dbsNorthwind![Orders].OpenRecordset(dbOpenDynaset)

strPosition = rstOriginal.Bookmark	' Save current record position.

rstDuplicate = rstOriginal.Clone ()	' Create duplicate Recordset.rstDuplicate.Bookmark = strPosition	' Go to same record.


Close Method Example

This example opens and then closes a database and a table-type Recordset object for the Customers table in the database.

Dim dbsNorthwind As Database, rstCustomers As Recordset

' Open database.

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Open table.

Set rstCustomers = dbsNorthwind.OpenRecordset("Customers")

...

rstCustomers.Close	' Close recordset.

dbsNorthwind.Close	' Close database.


CompactDatabase Method Example

This example uses CompactDatabase to compact a database and keeps a backup copy of the original database. The new database has the same locale as the source database, but is encrypted.

DBEngine.CompactDatabase "C:\Biblio.mdb","C:\BibNew.mdb","",dbEncrypt

...

Kill "C:\Biblio.BAK"

Name "C:\Biblio.mdb" As "C:\BIBLIO.BAK"

Name "C:\BibNew.mdb" As "C:\Biblio.mdb"

This example copies a database named Northwind.mdb and keeps a new, compacted copy named COPY.NEW. The new database is encrypted.

DBEngine.CompactDatabase "C:\Northwind.mdb", "C:\Copy.NEW","",dbEncrypt


CreateDatabase Method Example

This example uses CreateDatabase to create a new, encrypted Database object. The example customizes some properties of the new database, completes its structure, and then closes it.

 Dim wspDefault As Workspace, dbsDefault As Database, dbsNew As Database

Set wspDefault = DBEngine.Workspaces(0)

Set dbsDefault = wspDefault.OpenDatabase("Northwind.mdb")

If Dir$("NewDB.mdb") <> "" Then

Kill "NewDB.mdb"

Set dbsNew = wspDefault.CreateDatabase("NewDB.mdb", dbLangGeneral, _

dbEncrypt)

dbsNew.QueryTimeout = dbsDefault.QueryTimeout

...

' Complete structure of dbsNew, possibly using structure of dbsDefault.

...

dbsNew.Close

dbsDefault.Close


CreateField Method Example

This example creates a new Field object.

Dim dbsNorthwind As Database

Dim tdfEmployees As TableDef

Dim fldPhone As Field

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfEmployees = dbsNorthwind.TableDefs("Employees")

' Create new Field object.

Set fldPhone = tdfEmployees.CreateField("Phone", dbText)

' Set another property of fldPhone.

fldPhone.Size = 25	' Greater than longest phone number.

' Save fldPhone definition by appending it to Fields collection.

tdfEmployees.Fields.Append fldPhone

dbsNorthwind.Close


CreateGroup Method Example

This example creates a new Group object.

Dim grpManagers As Group, strManagersPID As String

strManagersPID = "2222abc"

' Create new Group object.

Set grpManagers = DBEngine.Workspaces(0).CreateGroup("Managers", _

strManagersPID)

' Create new group in workgroup by appending it to Groups collection.

Workspaces(0).Groups.Append grpManagers


CreateIndex Method Example

This example creates a new Index object.

Dim idxAnother As Index, fldLastName As Field

Dim tdfEmployees As TableDef, dbsNorthwind As Database

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfEmployees = dbsNorthwind.TableDefs("Employees")

' Create new Index object.

Set idxAnother = tdfEmployees.CreateIndex("Another")

Set fldLastName = idxAnother.CreateField("LastName")

idxAnother.Primary = False

idxAnother.Required = True

idxAnother.Fields.Append fldLastName

' Save Index definition by appending it to Indexes collection.

tdfEmployees.Indexes.Append idxAnother

tdfEmployees.Indexes.Delete "Another"

dbsNorthwind.Close


CreateProperty Method Example

This example creates a new Property object.

Dim prpPrivilege As Property

Dim dbsNorthwind As Database

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create new Property object.

Set prpPrivilege = dbsNorthwind.CreateProperty("Privilege")

' Set other properties of prpPrivilege.

prpPrivilege.Type = dbBoolean

prpPrivilege.Value = True

' Save Property definition by appending it to Properties collection.

dbsNorthwind.Properties.Append prpPrivilege


CreateQueryDef Method Example

This example creates a QueryDef named All Pubs with an SQL statement, and then creates a dynaset-type Recordset based on the query.

Dim dbsBiblio As Database, qdfAllPubs As QueryDef

Dim rstAllPubs As Recordset

' Open a database.

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

' Create a QueryDef.

Set qdfAllPubs = dbsBiblio.CreateQueryDef("All Pubs", _

"SELECT * FROM Publishers;")

' Create Recordset from query.

Set rstAllPubs = qdfAllPubs.OpenRecordset

...


CreateRelation Method Example

This example creates a new Relation object. In this case, the Customers table is related to a ValidStates table. Once established, the relationship requires that an entry exist in the ValidStates table corresponding to the Customers.CustState field before it can be added to the Customers table. Any changes to the State field that violate this relationship trigger a trappable error.

By setting the dbRelationUpdateCascade attribute, the Microsoft Jet database engine changes the Primary table Customers.CustState if a corresponding value changes in the ValidStates table. For example, if the ValidState entry TR was changed to TX, all Customers records having TR as a CustState code would be changed to TX.

Dim relTableOne As Relation

Dim dbsNorthwind As Database

Dim fldCustState As Field

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create new Relation object.

Set relTableOne = dbsNorthwind.CreateRelation("TableRelationOne")

relTableOne.Table = "Customers"	'Name the Primary Table.

relTableOne.ForeignTable = "ValidStates"	'Name the Foreign Table.

relTableOne.Attributes = dbRelationUpdateCascade

Set fldCustState = relTableOne.CreateField("CustState")

fldCustState.ForeignName = "StateCode"

relTableOne.Fields.Append fldCustState

' Save Relation definition by appending it to Relations collection.

dbsNorthwind.Relations.Append relTableOne


CreateTableDef Method Example

This example creates a new TableDef object in the Biblio.mdb database.

Dim tdfTitleDetail As TableDef, fldComments As Field

Dim dbsBiblio As Database

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

' Create new TableDef.

Set tdfTitleDetail = dbsBiblio.CreateTableDef("Title Detail")

' Add field to tdfTitleDetail.

Set fldComments = tdfTitleDetail.CreateField("Comments",dbMemo)

tdfTitleDetail.Fields.Append fldComments

' Save TableDef definition by appending it to TableDefs collection.

dbsBiblio.TableDefs.Append tdfTitleDetail


CreateUser Method Example

This example creates a new User object.

Dim usrPartner As User

Dim strManagersPID As String

strManagersPID = "1122aabb"

' Create new user account.

Set usrPartner = DBEngine.Workspaces(0).CreateUser("Partner", _
strManagersPID)

' Set other properties of usrPartner.

usrPartner.Password = "NewPassword"

' Save user account definition by appending it to Users collection.

DBEngine.Workspaces(0).Users.Append usrPartner

' Re-create usrPartner and append to Groups collection

Set usrPartner = DBEngine.Workspaces(0).CreateUser("Partner")

DBEngine.Workspaces(0).Groups(0).Users.Append usrPartner


CreateWorkspace Method Example

This example creates a new Workspace object named Special, and sets its UserName property to “guest”.

Dim wspSpecial As Workspace

' Create new workspace.

Set wspSpecial = DBEngine.CreateWorkspace("Special","guest", "")


Delete Method Example

This example finds a record in a Recordset and deletes it.

' Find the record you want to delete.

rstPublications.FindFirst "PubNum = 9"

If Not rstPublications.NoMatch Then	' Check if record found.

rstPublications.Delete	' Delete the record.

End If

This example adds and then deletes an Index from a TableDef.

Dim dbsBiblio As Database

Dim tdfAuthors As TableDef

Dim idxAuthorName As Index, fldAuthor As Field

' Open the database.

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

' Set the TableDef.

Set tdfAuthors = dbsBiblio.TableDefs("Authors")

Set idxAuthorName = tdfAuthors.CreateIndex("Author Name")

Set fldAuthor = idxAuthorName.CreateField("Author")

idxAuthorName.Fields.Append fldAuthor	' Add Field to Index.

' Append Index to TableDef.

tdfAuthors.Indexes.Append idxAuthorName

tdfAuthors.Indexes.Delete "Author Name"	' Delete the Index.


OpenRecordset, Edit, Update Methods Example

This example finds the first record in a Recordset object that matches the search criteria and opens it for editing. Then it changes the value in the Title field and saves the change using the Update method.

Dim strCriteria As String, strNewTitle As String

strCriteria = "Title = 'My Right Hand'"	' Create the criteria.

strNewTitle = "My Right Foot"	' Create a new title.

rstTitles.FindFirst strCriteria	' Make record current.

Do While Not rstTitles.NoMatch

rstTitles.Edit	' Open record.

rstTitles.Fields("Title") = strNewTitle	' Enter new title.

rstTitles.Update	' Save changes.

rstTitles.FindNext strCriteria

Loop

The following example achieves the same effect without using the Edit method.

' Create the criteria string.

strSQLQuery = "UPDATE Titles SET Title = 'My Right Foot'" & _

" WHERE Title = 'My Right Hand';"

dbsPublishers.Execute strSQLQuery	' Execute the query.

This example opens a Recordset object and locates each record whose Title field satisfies the search criteria and copies it to the copy buffer. The example then prepares the record for subsequent editing, changes the job title, and saves the change using the Update method.

Dim dbsNorthwind As Database, rstEmployees As Recordset

Dim strCriteria As String, strNewTitle As String

' Set search criteria.

strCriteria = "Title = 'Sales Representative'"

strNewTitle = "Account Executive"	' Set new job title.

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create dynaset.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", _
dbOpenDynaset)

rstEmployees.FindFirst strCriteria	' Find first occurrence.

' Loop until no matching records.

Do Until rstEmployees.NoMatch

With rstEmployees

   .Edit	' Enable editing.

   !Title = strNewTitle	' Change title.

   .Update	' Save changes.

   .FindNext strCriteria	' Find next occurrence.

End With

Loop	' End of loop.

Tip   Using an update query to change job titles might be more efficient. For example, you could use the following code to achieve the same results:

strSQL = "Update Employees Set Title = 'Account Executive' " & _
"WHERE Title = 'Sales Representative' "

dbsNorthwind.Execute strSQL


Execute Method Example

This example uses a Data control to execute an action query that updates all titles that have no value in the ISBN column in the Titles table. If there is an error, all changes are rolled back.

Dim strSQL as String

strSQL = "DELETE FROM Titles WHERE ISBN IS NULL"

dbsBiblio.Execute strSQL, dbFailOnError


FindFirst, FindLast, FindNext, FindPrevious Methods Example

This example uses FindFirst to find the first record matching the specified criteria in a Recordset object and then uses FindNext to find the next matching record.

Dim strCriteria As String

strCriteria = "State = 'NY'"	' Set the criteria.

rstAddress.FindFirst strCriteria	' Find first matching record.

If rstAddress.NoMatch = False Then	' Check if record is found.

rstAddress.FindNext strCriteria	' Find next matching record.

...

This example creates a dynaset-type Recordset object and then uses FindFirst to locate the first record satisfying the title condition.

Dim strCriteria As String

Dim dbsBiblio As Database, rstPublishers As Recordset

strCriteria = "State = 'NY'" 	' Define search criteria.

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

' Create a dynaset-type Recordset based on Publishers table.

Set rstPublishers = dbsBiblio.OpenRecordset("Publishers",dbOpenDynaset)

rstPublishers.FindFirst strCriteria	' Find first matching record.

If rstPublishers.NoMatch = False Then	' Check if record is found.

rstPublishers.FindNext strCriteria	' Find next matching record.

...


GetRows Method Example

The following example uses an SQL statement to retrieve three fields from an “Employees” table into a Recordset object.  It then uses the GetRows method to retrieve the first three records of the Recordset, and stores the selected records in a two-dimensional array. Each record is then printed, one field at a time, using the two array indexes to select specific fields and records.

Note To clearly illustrate how the array indexes are used, the example uses a separate statement to identify and print each field of each record. In practice, it would be more reliable to use two loops, one nested in the other, and provide integer variables for the indexes, to step through both dimensions of the array.

Sub GetRows_Test()

Dim dbsCurrent As Database, rstEmployees As Recordset
Dim varRecords As Variant

Set dbsCurrent = CurrentDB()
Set rstEmployees = dbsCurrent.OpenRecordset("SELECT FirstName, " & _
"LastName, Title FROM Employees", dbOpenSnapshot)

varRecords = rstEmployees.GetRows(3)

Debug.Print "First Name", "Last Name", "Title"

Debug.Print varRecords(0, 0),

Debug.Print varRecords(1, 0),

Debug.Print varRecords(2, 0)

Debug.Print varRecords(0, 1),

Debug.Print varRecords(1, 1),

Debug.Print varRecords(2, 1)

Debug.Print varRecords(0, 2),

Debug.Print varRecords(1, 2),

Debug.Print varRecords(2, 2)

End Sub


Move Method Example

This example creates a function that moves the current record position in a Recordset forward or back a specified number of records and provides an optional offset.

Sub MoveRelative (lngDistance As Long, strDirection As String, _

rstTarget As Recordset, varRelativeMark As Variant)

Dim strHere As String

strHere = rstTarget.Bookmark

strDirection = UCase(strDirection)

Select Case strDirection

Case "FWD":  lngDistance = Abs(lngDistance)

Case "BACK": lngDistance = Abs(lngDistance) * -1

Case Else: MsgBox "Incorrect calling argument"

End Select

If UCase(varRelativeMark) = "HERE" Then

rstTarget.Move lngDistance	' Move current record position.

Else

' Move relative to bookmark.

rstTarget.Move lngDistance, varRelativeMark

End If

' Move may not have been completed.

If rstTarget.EOF Or rstTarget.BOF Then Beep

End Sub


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Example

This example changes the job title of all sales representatives in a table named Employees. After opening the table, it uses MoveFirst to locate the first record and MoveNext to move to the next record. For each record satisfying the title condition, the example changes the title and saves the change using the Update method.

It's far more efficient to use the WHERE clause of an SQL statement to request the records you want to update than to test each record one at a time. The whole operation could be accomplished by using a single UPDATE statement, as shown in the following example.

Dim dbsNorthwind As Database, rstEmployees As Recordset

Dim strSelect as String

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

strSelect = "Select * FROM Employees WHERE Title = 'Sales Representative' "

' Open recordset.

Set rstEmployees = dbsNorthwind.OpenRecordset(strSelect)

Do Until rstEmployees.EOF	' Begin loop.

With rstEmployees

.Edit	' Enable editing.

!Title = "Account Executive"	' Change title.

.Update	' Save changes.

.MoveNext	' Locate next record.

End With

Loop	' End of loop.

rstEmployees.Close	' Close table.

dbsNorthwind.Close

Tips

Using an update query to change job titles might be more efficient. For example, you could use the following code to achieve the same results:

Dim strSelect as String

strSelect = "Update Employees Set Title = 'Account Executive' " _

"WHERE Title = 'Sales Representative' "

dbsNorthwind.Execute strSelect


NewPassword Method Example

This example changes the password of the existing user Pat Smith from My Secret to msMSApw. The user must be logged on as Pat Smith or as a member of the Admins group.

Workspaces(0).Users("Pat Smith").NewPassword "My Secret", "msMSApw"


OpenDatabase Method Example

This example opens the Employees table in the database in the default Workspace object. If the database can't be opened (for example, if it has already been opened for exclusive access by another user in a multiuser environment), an error occurs and a message is displayed. Then the example updates the Title field of the Employees table.

Function UpdateNorthwind () As Integer

Dim wspDefault As Workspace, dbsNorthwind As Database

Dim rstEmployees As Recordset

Dim intErrorCondition As Integer, intUpdateNorthwind As Integer

intUpdateNorthwind = True

intErrorCondition = False

On Error GoTo DBErrorHandler	' Enable error trapping.

Set wspDefault = DBEngine.Workspaces(0)

' Open database.

Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")

If intErrorCondition = False Then

On Error GoTo TableErrorHandler	' Enable error trapping.

' Open table.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")

If intErrorCondition = False Then

On Error GoTo EditErrorHandler	' Enable error trapping.

Do Until rstEmployees.EOF

If rstEmployees![Title] = "Sales Representative" Then

rstEmployees.Edit	' Enable editing.

rstEmployees![Title] = "Account Executive"

rstEmployees.Update	' Save changes.

End If

rstEmployees.MoveNext	' Move to next record.

Loop

End If

dbsNorthwind.Close	' Close database.

End If

On Error GoTo 0	' Disable error trapping.

Exit Function

DBErrorHandler:

intErrorCondition = True

intUpdateNorthwind = False

MsgBox "Can't open database.", vbExclamation

Resume Next

TableErrorHandler:

intErrorCondition = True

intUpdateNorthwind = False

MsgBox "Can't open Employees table.", vbExclamation

Resume Next

EditErrorHandler:

intErrorCondition = True

UpdateDb = False

MsgBox "Can't edit Employees table.", vbExclamation

Resume Next

End Function


Refresh Method Example

This example refreshes the Tables collection in a database in a multiuser environment in case another user has made changes.

Dim wspDefault As Workspace, dbsNorthwind As Database

' Get default workspace.

Set wspDefault = DBEngine.Workspaces(0)

' Open database.

Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")

...

' Refresh possibly changed collection.

dbsNorthwind.Containers("Tables").Documents.Refresh


RefreshLink Method Example

This example attaches a Paradox table named PDX_Author to a database opened for exclusive use, moves the connection to a different directory, and then refreshes the connection information.

Dim dbsPublishers As Database, tdfPDX_Author As TableDef

' Open database.

Set dbsPublishers = DBEngine.Workspaces(0).OpenDatabase _
("C:\CONTACTS\Biblio.mdb")

Set tdfPDX_Author = dbsPublishers.CreateTableDef _
("PDX_Author", dbAttachExclusive)

tdfPDX_Author.SourceTableName = "Author"

tdfPDX_Author.Connect = "Paradox 3.x; " _

& "DATABASE=C:\PDX\PUBS; PWD=books"

' Append to TableDefs collection.

dbsPublishers.TableDefs.Append tdfPDX_Author

' Move to new directory.

dbsPublishers.TableDefs!PDX_Author.Connect = "Paradox 3.x; " _

& "DATABASE=N:\PDX\PUBS; PWD=books"

' Refresh connection information.

dbsPublishers.TableDefs!PDX_Author.RefreshLink


RegisterDatabase Method Example

This example registers a SQL Server data source named PtLudlow and then opens the database MySQLDb on that server.

Using the Windows ODBC control panel icon is the preferred way to create, modify, or delete data source names.

Dim dbsLudlow As Database

Dim strAttribs As String

' Build keywords string.

strAttribs = "Description=SQL Server on server PtLudlow" & _
Chr$(13) & "OemToAnsi=No" & Chr$(13) & "Network=DBNMP3" & _
Chr$(13) & "Address=\\PTLUDLOW\PIPE\SQL\QUERY" & Chr$(13) & _
"Database=MySQLDb"

' Update ODBC.INI.

DBEngine.RegisterDatabase "PtLudlow", "SQL Server 32", True, strAttribs

' Open the database.

Set dbsLudlow = DBEngine.Workspaces(0).OpenDatabase("PtLudlow", _
False, False, "ODBC;")


RepairDatabase Method Example

This example attempts to repair a database named Northwind.mdb.

DBEngine.RepairDatabase "C:\Northwind.mdb"


Seek Method Example

This example uses Seek to locate the first record in the Publishers table where the PubID field is 3, using the existing primary key index.

Dim dbsBiblio As Database, rstPublishers As Recordset

' Open a database.

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

' Open a table.

Set rstPublishers = dbsBiblio.OpenRecordset("Publishers")

rstPublishers.Index = "PrimaryKey"	' Define current index.

rstPublishers.Seek "=", 3	' Seek record.

If rstPublishers.NoMatch Then...

This example uses the OpenDatabase method to directly open an installable ISAM database and then uses Seek to locate a record in a table in that database.

Dim dbsFoxData as Database, rstParts as Recordset

Dim varSaveHere as Variant

Set dbsFoxData = OpenDatabase("C:\FoxData", False, False,"Fox 2.5")

Set rstParts = dbsFoxData.OpenRecordset("PARTS.dbf", dbOpenTable)

' Choose record order and Seek index.

rstParts.Index = "PartNameIndex"

varSaveHere = rstParts.BookMark	' Save current location.

' Search for first instance of a chosen part.

rstParts.Seek "=", "Framis Lever"

If rstParts.NoMatch then 	' Test for success.

rstParts.BookMark = varSaveHere	' Seek not successful.

...

Else	' Seek worked; use current record.

Debug.Print rstParts!PartName

End If


Update Method Example

This example changes the Title field in the current record of a Recordset object and then uses the Update method to save the changes.

rstTitles.Edit	' Enable editing.

rstTitles.Fields("Title") = "My Right Foot"	' Change title.

rstTitles.Update	' Save changes.


AbsolutePosition Property Example

This example positions the current record to the nth record in a dynaset-type Recordset object.

Function MoveToRecord (intPosition As Long, rstTest As recordset) _
As Integer

rstTest.MoveLast

If rstTest.RecordCount > intPosition Then

rstTest.AbsolutePosition = intPosition

MoveToRecord = True

Else

MoveToRecord = False

End If

End Function


BOF and EOF Properties Example

This example uses the BOF and EOF properties to find the beginning and end of an Orders table. The example moves through the records from the beginning of the file to the end and then from the end to the beginning. Notice that there is no current record immediately following the first loop.

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstOrders = dbsNorthwind.OpenRecordset("Orders")	' Open Recordset.

Do Until rstOrders.EOF	' Do until end of file.
rstOrders.MoveNext	' Move to next record.
...
Loop

rstOrders.MoveLast	' Establish a current record.

Do Until rstOrders.BOF	' Do until beginning of file.
rstOrders.MovePrevious	' Move to previous record.

...
Loop

rstOrders.Close

dbsNorthwind.Close


Bookmark and Bookmarkable Properties Example

This example shows how you can save your place in a Recordset by saving a bookmark. Once saved, this bookmark can be applied to the Bookmark property to reposition the current record pointer to any location in the Recordset. The FindYear function works with the Biblio.mdb database.  It looks up all titles in a given Recordset published in a given year, and fills a string array with the bookmarks of any records that match.

Function FindYear (intYear As Integer, rstBooks As Recordset, _
avarRecord() As Variant) As Integer

Dim intCount As Integer

rstBooks.FindFirst "[Year Published] = " & intYear

If (rstBooks.NoMatch = True) Or (rstBooks.Bookmarkable = False) _
Then

FindYear = 0

Exit Function

Else

Do Until rstBooks.NoMatch = True

avarRecord(intCount) = rstBooks.Bookmark

rstBooks.FindNext "[Year Published] = " & intYear

intCount = intCount + 1

Loop

End If

FindYear = intCount

End Function


CacheSize and CacheStart Properties Example (Client/Server)

This example moves through all records in a Recordset twice; once with no cache and once with a 50 record cache.  The example then displays the performance statistics for the uncached and cached runs through the Recordset.

Dim wspDefault As Workspace, dbsPubs As Database

Dim tdfPerformanceTest As TableDef, rstRemote As Recordset

Dim strNoCache As String, strCache As String

Set wspDefault = DBEngine.Workspaces(0)

Set dbsPubs = wspDefault.OpenDatabase("PUBLISH.mdb")

Set tdfPerformanceTest = dbsPubs.CreateTableDef("TestData")

tdfPerformanceTest.Connect = "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

tdfPerformanceTest.SourceTableName = "dbo.roysched"

dbsPubs.TableDefs.Append tdfPerformanceTest

ConnectSource = True

Set rstRemote = dbsPubs.OpenRecordset("TestData")

MsgBox "This example moves through all records in the Recordset " & _

"twice; once with no cache and once with a 50 record cache."

' Start uncached run

tmStart = Timer

For i% = 1 To 2

    rstRemote.MoveFirst

    While Not rstRemote.EOF

        v = rstRemote(0)

        rstRemote.MoveNext

    Wend

Next i%

tmEnd = Timer

strNoCache = "Time without caching: " & Format$(tmEnd - tmStart) & _

    Chr$(13) & Chr$(10)

' Start cached run

rstRemote.MoveFirst

rstRemote.CacheStart = rstRemote.Bookmark

rstRemote.CacheSize = 50

tmStart = Timer

For i% = 1 To 2

    rstRemote.MoveFirst

    While Not rstRemote.EOF

        v = rstRemote(0)

        rstRemote.MoveNext

    Wend

Next i%

tmEnd = Timer

strCache = "Time with 50 record cache: " & Format$(tmEnd - tmStart) & _

    Chr$(13) & Chr$(10)

' Display performance results

MsgBox "Caching Performance Results:" & Chr$(13) & Chr$(10) & _

    strNoCache & strCache

rstRemote.Close

dbsPubs.Close


ConflictTable Property Example

This example finds the name of the conflict table containing the records that were not updated in a specific table during the synchronization, calls a custom routine for resolving the conflicts, deletes the record in the conflict table, and deletes the conflict table after all records have been processed.

Sub Resolve (dbsResolve As Database)

Dim tdfTest As TableDef, rstConflict As Recordset

For Each tdfTest In dbsResolve.TableDefs

If (tdfTest.ConflictTable <> " ") Then

Set rstConflict = dbsResolve.OpenRecordset _
(tdfTest.ConflictTable)

rstConflict.MoveFirst	' Process each record

While Not rstConflict.EOF

.

.	' Do conflict resolution

.

rstConflict.Delete	' Remove conflicting

rstConflict.MoveNext

Wend

rstConflict.Close

End If

Next tdfTest

End Sub


Connect and SourceTableName Properties Example

This example creates a TableDef object in the specified database; sets its Connect, Name, and SourceTableName properties; and then appends it to the TableDefs collection.

Function ConnectSource () As Integer

Dim dbsLocal As Database, tdfPDXAuthor As TableDef

Set dbsLocal = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfPDXAuthor = dbsLocal.CreateTableDef("PDXAuthor")

' Attach Paradox table Author in database C:\PDX\PUBLISH.

tdfPDXAuthor.Connect = "Paradox 4.X;DATABASE=C:\PDX\PUBLISH"

tdfPDXAuthor.SourceTableName = "Author"

dbsLocal.TableDefs.Append tdfPDXAuthor	' Attach table.

ConnectSource = True

End Function


Container Property Example

This example determines the name of the Container object to which a Document object belongs.

Sub Doc_Analyzer(docUnknown As Document)

Dim strContainerName As String

strContainerName = docUnknown.Container

Select Case strContainerName

Case "Tables"

...

Case "Databases"

...

Case "Forms"

...

Case Else

...

End Select

End Sub


Count Property Example

This example lists the names and total number of TableDef and QueryDef objects in the current database.

Dim dbsLocal As Database, intCount As Integer

Set dbsLocal = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

For intCount = 0 To dbsLocal.TableDefs.Count - 1
Debug.Print dbsLocal.TableDefs(intCount).Name
Next intCount

Debug.Print dbsLocal.TableDefs.Count

For intCount = 0 To dbsLocal.QueryDefs.Count - 1
Debug.Print dbsLocal.QueryDefs(intCount).Name
Next intCount

Debug.Print dbsLocal.QueryDefs.Count


DateCreated and LastUpdated Properties Example

This example determines the date and time when the Employees table was created and last updated.

Dim varCreation As Variant, varDesignChange As Variant

Dim rstEmployees As Recordset, dbsNorthwind As Database

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenTable)

varCreation = rstEmployees.DateCreated

varDesignChange = rstEmployees.LastUpdated


DesignMasterID Property Example

This example sets the DesignMasterID property to the ReplicaID property setting of another database, making that database the Design Master in the replica set. The old and new Design Masters are synchronized to update the design change.

' Open current Design Master in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strOldDM, True)

' Open new Design Master.

set newdmdb = DBEngine(0).OpenDatabase(strNewDB)

dbs.DesignMasterID = newdmdb.ReplicaID

dbs.Synchronize strNewDB,dbRepImpExpChanges

dbs.Close

newdmdb.Close


Error Object, Errors Collection, and Description, Number, and Source Properties Example

This example forces an error, traps it, and displays the Description, Number, and Source properties of the resulting Error object.

Sub ForceError()

Dim dbsTest As Database

On Error GoTo TestErrorHandler

Set dbsTest = OpenDatabase("DoesNotExist")

Exit Sub

TestErrorHandler:

Dim strError As String

Dim errObj As Error

strError = " "

For Each errObj in DBEngine.Errors

strError = strError & Format$(errObj.Number)

strError = strError & " : " & errObj.Description

strError = strError & " (" & errObj.Source & ") . "

strError = strError & Chr$(13) & Chr$(10)

Next

MsgBox strError

Resume Next

End Sub


DistinctCount Property Example

This example checks the DistinctCount property of an Index of a TableDef object opened on a table in the database.

Dim dbsNorthwind As Database, tdfCustomers As TableDef

Dim idxCurrent As Index

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfCustomers = dbsNorthwind!Customers

Set idxCurrent = tdfCustomers.Indexes(0)

Debug.Print idxCurrent.DistinctCount


EditMode Property Example

This example checks the EditMode property of a Recordset object and completes the update if the AddNew method has been invoked or the object is being edited.

Function PostChange(rstTarget as Recordset) As Integer

If (rstTarget.EditMode = dbEditAdd) or  _

(rstTarget.EditMode = dbEditInProgress) Then

rstTarget.Update

PostChange = True

Else

PostChange = False

End If

End Function


Filter Property Example

This example creates a dynaset-type Recordset that contains only records for orders shipped to the United Kingdom.

Dim dbsNorthwind As Database

Dim rstOrders As Recordset, rstFiltered As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset)	' Create dynaset-type Recordset.

rstOrders.Filter = "ShipCountry = 'UK'"	' Set filter condition.

Set rstFiltered = rstOrders.OpenRecordset()	' Create filtered

' dynaset.

Note   To change the contents of rstOrders, you must set its Filter property, and then open a second Recordset object based on rstOrders.

Tip   In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example:

Dim dbsNorthwind As Database, rstOrders As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstOrders = dbsNorthwind.OpenRecordset("SELECT * FROM Orders " & _

"WHERE ShipCountry = 'UK';")


ForeignName, ForeignTable, and Table Properties Example

This example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables - in this case, Table1 (the primary table) and Table2 (the foreign table) in the specified database. Field1 is the primary key in Table1, and Field2 is a foreign key in Table2. The relationship is one-to-many and referential integrity is enforced.

Function ForeignNameTable () As Integer

Dim dbsDefault As Database

Dim fldLocal As Field, relForeign As Relation

' Get database.

Set dbsDefault =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create new relationship and set its properties.

Set relForeign = dbsDefault.CreateRelation("MyRelation")

relForeign.Table = "Table1"

relForeign.ForeignTable = "Table2"

' Create field and set its properties.

Set fldLocal = relForeign.CreateField("Field1")

fldLocal.ForeignName = "Field2"

' Append field to relation and relation to database.

relForeign.Fields.Append fldLocal

dbsDefault.Relations.Append relForeign

dbsDefault.Close

End Function


HelpContext and HelpFile Properties Example

This example uses the HelpContext and HelpFile properties of an Error object to start the Microsoft Windows Help system. By default, the HelpFile property contains the name of the Microsoft Jet database engine error message Help file.

On Error Resume Next	' Suppress errors for demonstration purposes.

Err.Raise 3005    ' Use VBA to generate "Invalid database name" error.

Msg = "Press F1 or Help to see " & Errors(0).HelpFile & _
" topic for this error"

MsgBox Msg, , "Error: " & Errors(0).Description & _

Errors(0).HelpFile & Errors(0).HelpContext


Index and Unique Properties Example

This example adds a new index to a TableDef object in the Biblio.mdb database, makes that index the current index, and invokes the Seek method based on that index. The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.

Dim rstPublishers As Recordset, dbsBiblio As Database

Dim idxPubIDName As Index, fldPubID As Field, fldName As Field

Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set idxPubIDName = dbsBiblio.TableDefs("Publishers").CreateIndex _
("PubID Name")

Set fldPubID = idxPubIDName.CreateField("PubID")

idxPubIDName.Fields.Append fldPubID

Set fldName = idxPubIDName.CreateField("Name")

idxPubIDName.Fields.Append fldName

idxPubIDName.Unique = True

Debug.Print idxPubIDName.Fields	' Show Fields property.

' Append the new Index to the Indexes collection.

dbsBiblio.TableDefs("Publishers").Indexes.Append idxPubIDName

Set rstPublishers = dbsBiblio.OpenRecordset("Publishers",dbOpenTable)  'Open the table.

rstPublishers.Index = "PubID Name"	' Set table's current index.

rstPublishers.Seek "=", "27", "Yourdon Press"	' Look for Publisher.

If rstPublishers.NoMatch Then

rstPublishers.MoveFirst

Debug.Print "Not found"

Else

Debug.Print rstPublishers!Name

End If

rstPublishers.Close

This example sets the index for rstOrders to the primary key. (PrimaryKey is the default name of an Index object if the primary key is set in the table's Design view.) Next, it locates the record with a matching key field value of 10,050. Notice that the current index must be set before certain operations, such as the Seek method, can be performed.

Dim dbsNorthwind As Database, rstOrders As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenTable)

rstOrders.Index = "PrimaryKey"	' Set current index.

rstOrders.Seek "=", 10050	' Locate record.

...

rstOrders.Close	' Close recordset.

dbsNorthwind.Close	' Close database.


Inherit Property Example

This example sets the Table container’s Inherit property to True, and then sets the Permissions property to allow users to alter the security settings of documents.

Dim dbsNorthwind As Database, conTables As Container

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set conTables = dbsNorthwind.Containers("Tables")

conTables.Inherit = True

conTables.Permissions = dbSecWriteSec

dbsNorthwind.Close


Inherited Property Example

This example creates a Recordset object from a QueryDef object, creates a new property, and indicates whether the property is inherited. Then the example prints the name of each field in the Recordset and, for each property of each field, it prints the Name, Type, Value, and Inherited property value settings.

Dim dbsDefault As Database, qdfTest As QueryDef

Dim rstTest As Recordset, prpMoose As Property

Dim intField As Integer, intProp As Integer

Set dbsDefault =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set qdfTest = dbsDefault.QueryDefs(0)

Set prpMoose = qdfTest.CreateProperty("Moose",dbBoolean, True)

qdfTest.Properties.Append prpMoose

Set rstTest = qdfTest.OpenRecordset()

Debug.Print "Is qdfTest.Properties(""Moose"")inherited? "

Debug.Print qdfTest.Properties("Moose").Inherited

Debug.Print "Is rstTest.Properties(""Moose"")inherited? "

Debug.Print rstTest.Properties("Moose").Inherited

For intField = 0 To rstTest.Fields.Count - 1

Debug.Print rstTest.Fields(intField).Name

On Error Resume Next

For intProp = 0 To rstTest.Fields(intField).Properties.Count - 1

Debug.Print rstTest.Fields(intField).Properties(intProp).Name

Debug.Print rstTest.Fields(intField).Properties(intProp).Type

Debug.Print rstTest.Fields(intField).Properties(intProp).Value

Debug.Print rstTest.Fields(intField).Properties(intProp).Inherited

Next intProp

Next intField

dbsDefault.Close


IniPath Property Example

This example sets the path in the IniPath property to an application’s key in the Windows Registry.

Sub SetPathFirst()

Dim strPath As String

strPath = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MyApp\3.0\KeyFolder"

DBEngine.IniPath = strPath

End Sub


IsolateODBCTrans Property Example

This example opens a Workspace and sets IsolateODBCTrans to True before starting a transaction.

Dim wrkDefault As Workspace

Set wrkDefault = DBEngine.Workspaces(0)

wrkDefault.IsolateODBCTrans = True

wrkDefault.BeginTrans

' Execute query to ODBC database and complete transaction.

...

...


LockEdits Property Example

This example opens a dynaset-type Recordset and sets its LockEdits property to False. This enables optimistic locking so other users can change the database records at any time. Your application triggers a trappable error if the data changes before you use the Update method.

Sub ShowLockStatus()

Dim dbsNorthwind As Database, rstCustomers As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstCustomers = dbsNorthwind.OpenRecordset("Customers", _
dbOpenDynaset)

rstCustomers.LockEdits = True

OnError Goto ErrorHandler

rstCustomers.Edit	' Start editing.

On Error GoTo 0

rstCustomers.CancelUpdate

rstCustomers.Close

dbsNorthwind.Close

Exit Sub

ErrorHandler:

If Err = 3197 Then

Debug.Print "data changed"

Resume Next

Else

Debug.Print "some other error"

Resume Next

End If

End Sub


LoginTimeout Property Example

This example sets the LoginTimeout property to 120 seconds and then creates and runs a query on a database on an ODBC server.

Dim dbsNorthwind As Database

Dim qdfCustomers As QueryDef, rstCustomers As Recordset

DBEngine.LoginTimeout = 120	' Timeout in 2 minutes.

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create query.

Set qdfCustomers = dbsNorthwind.CreateQueryDef("All Cust", _
"SELECT * FROM Customers;")

qdfCustomers.Connect = "ODBC;DSN=Human Resources; " & _
"DATABASE=HRSRVR; UID=Smith; PWD=Sesame"

' Log in to server and run query.

Set rstCustomers = qdfCustomers.OpenRecordset()


Name Property Example

This example creates a TableDef object and then names it Parts ID.

Dim dbsNorthwind As Database, tdfPartsID As TableDef

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set tdfPartsID = dbsNorthwind.CreateTableDef()

tdfPartsID.Name = "Parts ID"

...	' Create fields.

dbsNorthwind.TableDefs.Append tdfPartsID


NoMatch Property Example

This example changes the job title of all sales representatives in an Employees table. It creates a dynaset-type Recordset and then uses FindFirst and FindNext to locate every record satisfying the criteria for the title. It prepares each record for editing, changes the title, and saves the change with the Update method.

Dim strCriteria As String, varSaveHere As Variant

Dim dbsNorthwind As Database, rstEmployees As Recordset

strCriteria = "Title = 'Sales Representative'"   ' Define search 	  ' criteria.

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create Recordset.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenDynaset)

varSaveHere = rstEmployees.Bookmark	' Save Bookmark.

rstEmployees.FindFirst strCriteria	' Locate first occurrence.

Do Until rstEmployees.NoMatch	' Loop until no matching records.

With rstEmployees

   .Edit	' Enable editing.

   !Title = "Account Executive"	' Change title.

   .Update	' Save changes.

   .FindNext strCriteria	' Locate next record.

End With

Loop	' End of loop.

rstEmployees.Bookmark = varSaveHere

Tip   In some situations, using an update query is faster.


ODBCTimeoutProperty Example

This example sets the ODBCTimeout property to 120 seconds and then creates a query and runs it on a database on an ODBC server.

Dim dbsNorthwind As Database

Dim qdfCustomers As QueryDef, rstCustomers As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Create query.

Set qdfCustomers = dbsNorthwind.CreateQueryDef("All Cust", _
"SELECT * FROM Customers;")

qdfCustomers.Connect = "ODBC;DSN=Human Resources; SERVER=HRSRVR: " & _
"UID=Smith; PWD=Sesame"

' Log in to server and run query.

qdfCustomers.ODBCTimeout = 120

Set rstCustomers = qdfCustomers.OpenRecordset()


Owner Property Example

This example changes the Owner property setting of a Document object after determining whether the current user has the appropriate permissions to do so.

Dim dbsNorthwind As Database, docTest As Document

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set docTest = dbsNorthwind.Containers(0).Documents(0)

If (docTest.Permissions And dbSecWriteOwner) <> 0  Then

docTest.Owner = "SomebodyElse"

End If


Password and PID Properties Example

This example creates a new User object and sets the Name, PID, and Password properties for the new object before appending it to the Users collection.

Dim usrMyself As User, wrkDefault As Workspace

...

Set wrkDefault = DBEngine.Workspaces(0)   ' Get default workspace.

' Create, specify, and append new User object.

Set usrMyself = wrkDefault.CreateUser("Pat Smith")

usrMyself.PID = "abc123DEF456"

usrMyself.Password = "MySecret"

wrkDefault.Users.Append usrMyself


PercentPosition Property Example

This example displays the current position of a record in a Recordset in a message box.

Dim dbsNorthwind As Database, rstEmployees As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Open table.

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")

' Set current index.

rstEmployees.Index = "Last Name"

...

...	' Move among the records.

...

' Display current position.

MsgBox("Current position is " & rstEmployees.PercentPosition & " %.")


Permissions Property Example

This example prints the Permissions property setting of a Document object for the current user.

Dim dbsNorthwind As Database, docTest As Document

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set docTest = dbsNorthwind.Containers(0).Documents("MyDoc")

Debug.Print docTest.Permissions


Primary Property Example

In the Biblio.mdb database, this example creates a new Table and primary key Index object and then adds the Table to the TableDefs collection of a Database.

Dim dbsBiblio As Database , tdfBookTypes As TableDef

Dim idxPrimaryKey As Index, fldTypeNum As Field, fldType As Field

' Open the Database.

Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

Set tdfBookTypes = dbsBiblio.CreateTableDef("Book Types")

' Create and Set fldTypeNum field Set fldTypeNum = tdfBookTypes.CreateField("TypeNum",dbLong)

' Add fldTypeNum field to TableDef.

tdfBookTypes.Fields.Append fldTypeNum

' Create and Set fldType field properties.

Set fldType = tdfBookTypes.CreateField("Type",dbText)

fldType.Size = 15	' Set Size property of text field.

' Add fldType field to TableDef.

tdfBookTypes.Fields.Append fldType

Set idxPrimaryKey = tdfBookTypes.CreateIndex("PrimaryKey")

With idxPrimaryKey	' Set properties in new Index.

   .Name = "PrimaryKey"

   .Unique = True

   .Primary = True

   .Fields = "TypeNum"

End With

' Add Index to TableDefs collection.

idxPrimaryKey.fields.Append idxPrimaryKey.CreateField("TypeNum")

tdfBookTypes.Indexes.Append idxPrimaryKey

dbsBiblio.TableDefs.Append tdfBookTypes	' Append TableDef to database.

dbsBiblio.Close


QueryTimeout Property Example

This example opens the specified database and sets the QueryTimeout property to 120 seconds.

Dim dbsNorthwind As Database

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

dbsNorthwind.QueryTimeout = 120


RecordCount Property Example

This example creates a Recordset object based on the Employees table and then determines the number of records in the Recordset.

Dim dbsNorthwind As Database, rstEmployees As Recordset

Dim lngTotal As Long

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")

rstEmployees.MoveLast

lngTotal = rstEmployees.RecordCount

If lngTotal = -1 Then

Debug.Print "Count not available."

End If


RecordsAffected Property Example

This example prints the number of records updated by an action query.

Dim dbsBiblio As Database, lngResults As Long

Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")

dbsBiblio.Execute "Update Titles Set [Year Published] = 1994 " _

& " WHERE Title = 'To Kill an SQL Query' "

lngResults = dbsBiblio.RecordsAffected

Debug.Print lngResults & " records were changed."

dbsBiblio.Close


Restartable Property and Requery Method Example

This example determines the Restartable property setting of a dynaset-type Recordset and then uses the Requery method on the Recordset.

Dim dbsNorthwind As Database, rstChangeOften As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstChangeOften = dbsNorthwind.OpenRecordset _

("Table That Changes Often", dbOpenDynaset)

If rstChangeOften.Restartable = True Then

rstChangeOften.Requery

End If

dbsNorthwind.Close


ReturnsRecords Property Example

The following example creates an SQL pass-through query that returns records from an external database.

Dim dbsNorthwind As Database, qdfPassThrough As QueryDef

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set qdfPassThrough = dbsNorthwind.CreateQueryDef("October " & _

"Orders","SELECT * From Orders WHERE ShipCity = 'London'")

dbsNorthwind.Connect = "ODBC; DSN=MySQLDBDSN;  " _

& " UID=Chrissy;PWD=FourOh;"

qdfPassThrough.ReturnsRecords = True


Size and Type Properties Example

This example creates a new Field object with a Text field type, sets its Name property to Fax Phone and its Size property to 20, and appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Function SizeType() As Integer

Dim dbsNorthwind As Database

Dim fldFaxPhone As Field, tdfEmployees As TableDef

' Open database.

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Get existing table reference.

Set tdfEmployees = dbsNorthwind.TableDefs("Employees")

' Create Field object.

Set fldFaxPhone = tdfEmployees.CreateField("Fax Phone")

' Set field properties.

fldFaxPhone.Type = dbText

fldFaxPhone.Size = 20

' Append fldFaxPhone to Fields collection.

tdfEmployees.Fields.Append fldFaxPhone

SizeType = True

End Function

You can also use the CreateField method if you provide name, type, and size as arguments.

Set fldFaxPhone = tdfEmployees.CreateField("Fax Phone", dbText, 20)


Sort Property Example

This example uses the Sort property to set the sort order of a dynaset-type Recordset based on an Orders table. The records in rstSorted will be in ascending Ship Country order.

Dim dbsNorthwind As Database

Dim rstOrders As Recordset, rstSorted As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset)

rstOrders.Sort = "ShipCountry"	' Set sort order.

Set rstSorted = rstOrders.OpenRecordset()	' Create second dynaset.

Tip   In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example.

Dim dbsNorthwind As Database, rstOrders As Recordset

Dim strSelect As String

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

strSelect = "SELECT * FROM Orders ORDER BY ShipCountry;"

Set rstOrders = dbsNorthwind.OpenRecordset(strSelect)


SourceField and SourceTable Properties Example

This example creates a Recordset object using an SQL statement that creates aliases for fields in two different tables in the database. The example then prints the name of the field, the original table, and the original field.

Function SourceInfo () As Integer

Dim dbsNorthwind As Database

Dim rstEmployCustID As Recordset, fldEnum As Field

Dim strSelect As String, intStep As Integer

' Open database.

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

' Construct SQL statement.

strSelect = "SELECT EmployeeID As EmpID, CustomerID As " & _

"CustID FROM Employees, Customers;"

Set rstEmployCustID = dbsNorthwind.OpenRecordset(strSelect)

For intStep = 0 To rstEmployCustID.Fields.Count - 1

Set fldEnum = rstEmployCustID.Fields(intStep)

Debug.Print fldEnum.Name	' Print field name.

Debug.Print fldEnum.SourceTable	' Print original table name.

Debug.Print fldEnum.SourceField	' Print original field name.

Next intStep

SourceInfo = True

End Function


SQL Property Example

This example creates a query based on an Orders table. The query selects all orders that have a Freight value greater than 10.

Dim dbsNorthwind As Database, qdfLargeFrt As QueryDef

Dim rstFromQuery As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set qdfLargeFrt = dbsNorthwind.CreateQueryDef("Large Freight")

qdfLargeFrt.SQL = "SELECT * FROM Orders WHERE Freight > 10;"

Set rstFromQuery = qdfLargeFrt.OpenRecordset(dbOpenSnapshot)


Updatable Property Example

This example adds a record to a Recordset object if the object's Updatable property setting is True.

Dim dbsNorthwind As Database, rstUnknown As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstUnknown = dbsNorthwind.OpenRecordset("Unfamiliar Table")

If rstUnknown.Updatable = True Then

rstUnknown.AddNew

rstUnknown("MyField") = "Some new data"

rstUnknown.Update

End If

dbsNorthwind.Close


UserName Property Example

This example sets the access permissions for a table named MyTable in the specified database for a user named Millicent to read-only. The code then checks to see if Millicent has permission to add records.

Dim wrkDefault As Workspace, dbsNorthwind As Database

Dim docMyTable As Document

...

Set wrkDefault = DBEngine.Workspaces(0)

Set dbsNorthwind = wrkDefault.OpenDatabase("Northwind.mdb")

...

Set docMyTable = dbsNorthwind.Containers("Tables")![MyTable]

docMyTable.UserName = "Millicent"

docMyTable.Permissions = dbSecRetrieveData

If(docMyTable.Permissions and dbSecInsertData) > 0 Then

Debug.Print "Millicent can insert data."

Else

Debug.Print "Millicent can't insert data."

End If

...


Version Property Example

This example checks the version number of the Microsoft Jet database engine and splits it into the version number and release number. The example doesn't check for an invalid string.

Dim strDBVersion As String, strJetVersion As String

Dim strJetRelease As String

Dim intDot As Integer

...

strDBVersion = DBEngine.Version

intDot = InStr(strDBVersion, ".")

strJetVersion = Left$(strDBVersion, intDot - 1)

strJetRelease = Right$(strDBVersion, Len(strDBVersion) - intDot)

...


CreateQueryDef, OpenDatabase, OpenRecordset Methods and SQL Property Example (Client/Server)

This example queries the table of titles in the Microsoft SQL Server sample database Pubs and returns the title and title identifier of the best-selling book. The example then queries the table of authors and instructs the user to send a bonus check to each author based on his or her royalty share (the total bonus is $1,000 and each author should receive a percentage of that amount).

Dim wspDefault As Workspace, dbsPubs As Database

Dim qdfBonusEarners As QueryDef, qdfGetBestSeller As QueryDef

Dim rstTopSeller As Recordset, rstBonusRecipients As Recordset

Dim strAuthorList As String, intNumAuthors As Integer

Dim intBonusAmount As Integer, intCounter As Integer

Set wspDefault = DBEngine.Workspaces(0)

Set dbsPubs = wspDefault.OpenDatabase("PUBLISH.mdb")

' Get best-selling title identifier.

Set qdfGetBestSeller = dbsPubs.CreateQueryDef("BestSeller")

qdfGetBestSeller.Connect = "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

qdfGetBestSeller.SQL = "SELECT title, title_id FROM dbo.titles " & _

    "ORDER BY ytd_sales DESC"

Set rstTopSeller = qdfGetBestSeller.OpenRecordset()

rstTopSeller.MoveFirst

' Instruct user to send a bonus check to each author.

Set qdfBonusEarners = dbsPubs.CreateQueryDef("BonusDisbursement")

qdfBonusEarners.Connect = "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

qdfBonusEarners.SQL = "SELECT * FROM dbo.titleauthor " & _

    "WHERE title_id = " & "'" & rstTopSeller!title_id & "'"

Set rstBonusRecipients = qdfBonusEarners.OpenRecordset()

rstBonusRecipients.MoveLast

intNumAuthors = rstBonusRecipients.RecordCount

rstBonusRecipients.MoveFirst

intCounter = 0

While intCounter < intNumAuthors

    intBonusAmount = 10 * rstBonusRecipients!royaltyper

    strAuthorList = strAuthorList & rstBonusRecipients!au_id & ":  $" & _

    intBonusAmount & Chr$(13) & Chr$(10)

    intCounter = intCounter + 1

    rstBonusRecipients.MoveNext

Wend

MsgBox "Please send a check to the following authors in the" & _

    " amounts shown:" & Chr$(13) & Chr$(10) & strAuthorList & _

    "for outstanding sales of " & rstTopSeller!title

rstTopSeller.Close

rstBonusRecipients.Close

dbsPubs.Close


CreateTableDef, FillCache Methods and SourceTableName Property Example (Client/Server)

This example moves through all records in a Recordset twice; once with no cache and once with a 50-record cache. The example then displays the performance statistics for the uncached and cached runs through the Recordset.

Dim wspDefault As Workspace, dbsPubs As Database

Dim tdfPerformanceTest As TableDef, rstRemote As Recordset

Dim strNoCache As String, strCache As String

Set wspDefault = DBEngine.Workspaces(0)

Set dbsPubs = wspDefault.OpenDatabase("PUBLISH.mdb")

Set tdfPerformanceTest = dbsPubs.CreateTableDef("TestData")

tdfPerformanceTest.Connect = "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

tdfPerformanceTest.SourceTableName = "dbo.roysched"

dbsPubs.TableDefs.Append tdfPerformanceTest

ConnectSource = True

Set rstRemote = dbsPubs.OpenRecordset("TestData")

MsgBox "This example moves through all records in the Recordset " & _

"twice; once with no cache and once with a 50 record cache."

' Start uncached run

tmStart = Timer

For i% = 1 To 2

    rstRemote.MoveFirst

    While Not rstRemote.EOF

        v = rstRemote(0)

        rstRemote.MoveNext

    Wend

Next i%

tmEnd = Timer

strNoCache = "Time without caching: " & Format$(tmEnd - tmStart) & _

    Chr$(13) & Chr$(10)

' Start cached run

rstRemote.MoveFirst

rstRemote.FillCache (50)

tmStart = Timer

For i% = 1 To 2

    rstRemote.MoveFirst

    While Not rstRemote.EOF

        v = rstRemote(0)

        rstRemote.MoveNext

    Wend

Next i%

tmEnd = Timer

strCache = "Time with 50 record cache: " & Format$(tmEnd - tmStart) & _

    Chr$(13) & Chr$(10)

' Display performance results

MsgBox "Caching Performance Results:" & Chr$(13) & Chr$(10) & _

    strNoCache & strCache

rstRemote.Close

dbsPubs.Close


Connect and ReturnsRecords Properties Example (Client/Server)

This example selects the top five book titles from a Microsoft SQL Server database based on year-to-date sales amounts. In the event of an exact match in sales amounts, the example increases the size of the list displaying the results of the query and prints a message explaining why this occurred.

Dim wspDefault As Workspace, dbsPubs As Database

Set wspDefault = DBEngine.Workspaces(0)

Set dbsPubs = wspDefault.OpenDatabase("PUBLISH.mdb")

ConnectSource = True

Set qdfPassThrough = dbsPubs.CreateQueryDef("CompleteBookList")

qdfPassThrough.Connect = "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

qdfPassThrough.SQL = "SELECT * FROM dbo.titles " & _

    "ORDER BY ytd_sales DESC"

qdfPassThrough.ReturnsRecords = True

Set qdfLocal = dbsPubs.CreateQueryDef("TopFiveBestSellers")

qdfLocal.SQL = "SELECT TOP 5 title FROM CompleteBookList"

Set rstFromQuery = qdfLocal.OpenRecordset()

strMessageText = "Our top 5 best selling books are: " & Chr$(13) & Chr$(10)

While Not rstFromQuery.EOF

    strBookList = strBookList & rstFromQuery![title] & Chr$(13) & Chr$(10)

    rstFromQuery.MoveNext

Wend

If rstFromQuery.RecordCount > 5 Then

    strBookList = strBookList & "(There was a tie for fifth " & _

        "position, resulting in " & rstFromQuery.RecordCount & _

        " books in the list.)"

End If

MsgBox strMessageText & strBookList

rstFromQuery.Close

dbsPubs.Close