DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 1.3 Connecting to a Password-Protected Access Database

Problem

You want to connect to a Microsoft Access database that has a database password.

Solution

Use the Jet OLEDB:Database Password attribute in the connection string to specify the password.

The sample code contains a single event handler:

Connect Button.Click

Creates and opens a connection to a password-secured Microsoft Access database using the OLE DB .NET data provider. Information about the database is displayed from the properties of the OleDbConnection object.

The C# code is shown in Example 1-3.

Example 1-3. File: AccessPasswordForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.OleDb;

//  . . . 

private void connectButton_Click(object sender, System.EventArgs e)
{
    StringBuilder result = new StringBuilder( );

    // Build the connections string incorporating the password.
    String connectionString =
        ConfigurationSettings.AppSettings["MsAccess_Secure_ConnectString"]+
        "Jet OLEDB:Database Password=" + passwordTextBox.Text + ";";

    result.Append("ConnectionString: " + Environment.NewLine +
        connectionString + Environment.NewLine + Environment.NewLine);

    OleDbConnection conn = new OleDbConnection(connectionString);
    try
    {
        conn.Open( );

        // Retrieve some database information.
        result.Append(
            "Connection State: " + conn.State + Environment.NewLine +
            "OLE DB Provider: " + conn.Provider +
            Environment.NewLine +
            "Server Version: " + conn.ServerVersion +
            Environment.NewLine);

        conn.Close( );
        result.Append("Connection State: " + conn.State);
    }
    catch(System.Data.OleDb.OleDbException ex)
    {
        conn.Close( );
        result.Append("ERROR: " + ex.Message);
    }

    resultTextBox.Text = result.ToString( );
}

Discussion

A Microsoft Access database password requires that users enter a password to obtain access to the database and database objects. This is also known as share-level security. A password does not allow groups or users to have distinct levels of access or permissions. Anyone with the password has unrestricted access to the database.

The Set Database command from the Tools Security menu is used to set up a database password.

The OLE DB provider for Microsoft Jet has several provider-specific connection string attributes in addition to those defined by ADO.NET. To open a database secured by a Microsoft Access database password, use the Jet OLEDB:Database Password attribute in the connection string to specify the password. This corresponds to the OLE DB property DBPROP_JETOLEDB_DATABASEPASSWORD.

A Microsoft Access database password does not provide strong security and should only be used as a simple deterrent.

    [ Team LiB ] Previous Section Next Section