Deployment Tools Foundation
Working with MSI Databases
Development Guide > MSI Databases

### Querying a database

        using (Database db = new Database("product.msi", DatabaseOpenMode.ReadOnly))
        {
            string value = (string) db.ExecuteScalar(
                "SELECT `Value` FROM `Property` WHERE `Property` = '{0}'", propName);
        }

1. Create a new Database instance referring to the location of the .msi or .msm file.

2. Execute the query:

- The ExecuteScalar method is a shortcut for opening a view, executing the view, and fetching a single value.
- The ExecuteQuery method is a shortcut for opening a view, executing the view, and fetching all values.
- Or do it all manually with Database.OpenView, View.Execute, and View.Fetch.

### Updating a binary

        Database db = null;
        View view = null;
        Record rec = null;
        try
        {
            db = new Database("product.msi", DatabaseOpenMode.Direct);
            view = db.OpenView("UPDATE `Binary` SET `Data` = ? WHERE `Name` = '{0}'", binName))
            rec = new Record(1);
            rec.SetStream(1, binFile);
            view.Execute(rec);
            db.Commit();
        }
        finally
        {
            if (rec != null) rec.Close();
            if (view != null) view.Close();
            if (db != null) db.Close();
        }

1. Create a new Database instance referring to the location of the .msi or .msm file.

2. Open a view by calling one of the Database.OpenView overloads.

- Parameters can be substituted in the SQL string using the String.Format syntax.

3. Create a record with one field containing the new binary value.

4. Execute the view by calling one of the View.Execute overloads.

- A record can be supplied for substitution of field tokens (?) in the query.

5. Commit the Database.

6. Close the handles.

### About handles

Handle objects (Database, View, Record, SummaryInfo, Session) will remain open until they are explicitly closed or until the objects are collected by the GC. So for the tightest code, handle objects should be explicitly closed when they are no longer needed, since closing them can release significant resources, and too many unnecessary open handles can degrade performance. This is especially important within a loop construct: for example when iterating over all the Records in a table, it is much cleaner and faster to close each Record after it is used.

The handle classes in the managed library all extend the InstallerHandle class, which implements the IDisposable interface. This makes them easily managed with C#'s using statement. Alternatively, they can be closed in a finally block.

As a general rule, methods in the library return new handle objects that should be managed and closed by the calling code, while properties only return a reference to a prexisting handle object.

See also:

- MSI Diff Sample Tool
- Database Class