C# Database Example

[TOC]

using System;
using System.Data;
using System.Data.SqlClient;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Core.Examples.CSharp
{
  /// <summary>
  /// A .NET example in C# showing how to use ADO.NET data structures with matrices.
  /// </summary>
  class DatabaseExample
  {
    static void Main(string[] args)
    {
      Console.WriteLine();

      // Set up "database"
      DataTable table = new DataTable();
      table.Columns.Add("column1", typeof(double));
      table.Columns.Add("column2", typeof(double));
      object[] data = new object[2];
      data[0] = 4.5d;
      data[1] = 3.2d;
      table.Rows.Add(data);
      data[0] = -2.4d;
      data[1] = 99;
      table.Rows.Add(data);

      // Create matrix
      DoubleMatrix A = new DoubleMatrix(table);
      Console.WriteLine("A: ");
      Console.WriteLine(A.ToTabDelimited());

      // Change matrix by incrementing
      A++;
      Console.WriteLine("A incremented:");
      Console.WriteLine(A.ToTabDelimited());

      // Refresh data table 
      table = A.ToDataTable();

      // Insert into a database
      //      DataSet dataSet = new DataSet();
      //      dataSet.Tables.Add( table );
      //      SqlConnection connection = new SqlConnection( "connectionString" );
      //      connection.Open();
      //      SqlDataAdapter adapter = new SqlDataAdapter( "SELECT * FROM Values", connection );
      //      adapter.Update( dataSet );
      //      connection.Close();

      // Select rows where column1 is positive
      DataRow[] rows = table.Select("column1 > 0");

      // Make new matrix of resulting rows.
      A = new DoubleMatrix(rows);
      Console.WriteLine("A from database:");
      Console.WriteLine(A.ToTabDelimited());

      Console.WriteLine();
      Console.WriteLine("Press Enter Key");
      Console.Read();

    } // Main

  }// class

}// namespace

[TOC]