Accessing a local database via JavaScript

WARNING: This is NOT a secure method of accessing a database. The code below is strictly for demonstration purposes. Using it in a production environment is strongly discouraged.

Having said that, there are limited cases where the following can prove useful. In this case, creating an HTML Application file (HTA), or a local HTML file to access local data in an MS Access database.

The reason for choosing this method over other options such as designing a VBA macro, or more complex solutions requiring a server, is because it is simple, very lightweight, and allows for considerably more versatility in UI design than a similar solution in VBA would provide.

function getScalarValueFromDB() {
    var connection = new ActiveXObject("ADODB.Connection");
    var connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyDatabaseFolder\\MyAccessDatabase.mdb;";
    connection.Open(connectionstring);

    var rs = new ActiveXObject("ADODB.Recordset");
    rs.Open("SELECT ColumnOne FROM MainTable;", connection);
    alert(rs.Fields("ColumnOne"));
    
    rs.close();
    connection.close();
}

The JavaScript function above retrieves a value from one column in a fictitious Microsoft Access Database and displays it using the alert() function.

This code can only work in Internet Explorer (tested on version 11). To run it, simply place it inside <script> tags like you would any other JavaScript code.

Leave a Reply

Your email address will not be published. Required fields are marked *