Database (macros)

You can use low level System calls to access a database. These examples demonstrate the use of the SqlDataReader. The example below shows the macro commands required to achieve this;

 

Write to an SQL database

// Connection string (For windows login use Integrated Security=SSPI;):
var connectionString = "Server=172.01.02.03;Database=MYDB;User Id=chuck;Password=1234";

// Open database connection
var connection = OpenDatabaseConnection(connectionString);

// Update database with sql file
var sqlFile = "C:\\Temp\\myscript.sql";
print(ExecuteSqlScriptFile(connection, sqlFile));

// Close database connection
connection.Close();

function OpenDatabaseConnection(connectionString) {
  try {
    var connection = new System.Data.SqlClient.SqlConnection(connectionString);
    connection.Open();
    return connection;
  }
  catch (err) {
    print("Connection Error: " + err);
  }
  return null;
}

function ExecuteSqlScriptFile(connection, scriptFile) {
  if (System.IO.File.Exists(scriptFile) == false) {
    print("Unable to open sql file " + scriptFile);
    return;
  }
  try {
    var scriptContent = System.IO.File.ReadAllText(scriptFile);
    var cmd = new System.Data.SqlClient.SqlCommand(scriptContent, connection);
    var result = cmd.ExecuteNonQuery();
  }
  catch (err) {
    print("ExecuteSqlScripts error: " + err);
  }
  return result;
}

 

Read from an SQL database

// Connection string (For windows login use Integrated Security=SSPI;):
var connectionString = "Server=172.01.02.03;Database=MYDB;User Id=chuck;Password=1234";

// Open database connection
var connection = OpenDatabaseConnection(connectionString);

// Query database
var cmd = new System.Data.SqlClient.SqlCommand("Select * from Equipment", connection);
var data = cmd.ExecuteReader();

// Display the first and second fields returned from the query (string and value)
// FieldCount=Field count, GetName=Column name, GetString=Field data, GetValue=Field value
if (data.FieldCount > 0) {
  print(data.GetName(0) + ":" + data.GetName(1));
  while (data.Read()) {
    print(data.GetString(0) + ":" + data.GetValue(1));
  }
}

// Close database connection
connection.Close();

function OpenDatabaseConnection(connectionString) {
  try {
    var connection = new System.Data.SqlClient.SqlConnection(connectionString);
    connection.Open();
    return connection;
  }
  catch (err) {
  print("Connection Error: " + err);
  }
  return null;
}

 

The following examples use the OLEDB components that are normally supplied with MS Office. A separate install for these components to install on a machine without MS Office can be downloaded from the MSDN site.

The error produced when these components are missing is;

"'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine"

 

Read from an Excel spreadsheet

Sample code

Read from an Access database

Sample code