Create Connection

   
 


using System;
using System.Data;
using System.Data.Common;

class MainClass {
    public static void Main(string[] args) {
        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        using (IDbConnection con = factory.CreateConnection()) {
            con.ConnectionString = @"Data Source = .sqlexpress;Database = Northwind; Integrated Security=SSPI";
            using (IDbCommand com = con.CreateCommand()) {
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "Ten Most Expensive Products";
                con.Open();
                using (IDataReader reader = com.ExecuteReader()) {
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine("Price of the Ten Most Expensive Products.");
                    while (reader.Read()) {
                        Console.WriteLine("  {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]);
                    }
                }
            }
        }
    }
}

    


Use DB2Connection class to connect to a DB2 database

   


using System;
using System.Data;
using IBM.Data.DB2;

class Db2Connect{
   static void Main() {
       string connString = @"database = sample;";

       DB2Connection conn = new DB2Connection(connString);

       try {
         conn.Open();
         Console.WriteLine("Connection opened.");

         // Display connection properties
         Console.WriteLine("Connection Properties:");   
         Console.WriteLine("	Connection String: {0}", conn.ConnectionString);    
         Console.WriteLine("	Database: {0}",conn.Database);   
         Console.WriteLine("	ServerVersion: {0}",conn.ServerVersion);
         Console.WriteLine("	State: {0}",conn.State);
      } catch (DB2Exception e) {
         Console.WriteLine("Error: " + e);  
      } finally  {
         conn.Close();
         Console.WriteLine("Connection closed.");
      }
   }
}


           
          


OleDbConnection Connect to DB2: DB2 connection string

   

using System;
using System.Data;
using System.Data.OleDb;

class Db2Connect{
   static void Main() {
      string connString = @"provider = IBMDADB2.1;persist security info = false;data source = sample;";

      OleDbConnection conn = new OleDbConnection(connString);

      try
      {
         conn.Open();
         Console.WriteLine("Connection opened.");

         Console.WriteLine("Connection Properties:");   
         Console.WriteLine("	Connection String: {0}", conn.ConnectionString);    
         Console.WriteLine("	Database: {0}",conn.Database);   
         Console.WriteLine("	DataSource: {0}",conn.DataSource);
         Console.WriteLine("	ServerVersion: {0}",conn.ServerVersion);
         Console.WriteLine("	State: {0}",conn.State);
      } catch (OleDbException e) {
         Console.WriteLine("Error: " + e);  
      } finally {
         conn.Close();
         Console.WriteLine("Connection closed.");
      }
   }
}



           
          


use the Find() and FindRows() methods of a DataView to find DataRowView objects

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

class FindingDataRowViews {
public static void Main() {
SqlConnection mySqlConnection =
new SqlConnection(
“server=localhost;database=Northwind;uid=sa;pwd=sa”
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
“SELECT CustomerID, CompanyName, Country ” +
“FROM Customers”;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, “Customers”);
mySqlConnection.Close();
DataTable customersDT = myDataSet.Tables[“Customers”];

string filterExpression = “Country = 'UK'”;
string sortExpression = “CustomerID”;
DataViewRowState rowStateFilter = DataViewRowState.OriginalRows;

DataView customersDV = new DataView();
customersDV.Table = customersDT;
customersDV.RowFilter = filterExpression;
customersDV.Sort = sortExpression;
customersDV.RowStateFilter = rowStateFilter;

foreach (DataRowView myDataRowView in customersDV) {
for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); } int index = customersDV.Find("BSBEV"); Console.WriteLine("BSBEV found at index " + index + " "); DataRowView[] customersDRVs = customersDV.FindRows("BSBEV"); foreach (DataRowView myDataRowView in customersDRVs) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); } } } [/csharp]

Create DataView through DataTable

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

class DataViewExample
{
static void Main()
{
string connString = “server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI”;
string sql = @”select * from employee”;
SqlConnection conn = new SqlConnection(connString);

try {
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, conn);

DataSet ds = new DataSet();
da.Fill(ds, “employee”);

DataTable dt = ds.Tables[“employee”];

DataView dv = new DataView(dt,”lastname = 'Z'”, “lastname”, DataViewRowState.CurrentRows);

foreach (DataRowView drv in dv)
{
for (int i = 0; i < dv.Table.Columns.Count; i++){ Console.Write(drv[i] + " "); } } } catch(Exception e) { Console.WriteLine("Error: " + e); } finally { conn.Close(); } } } [/csharp]

illustrates the use of a DataView object to filter and sort rows

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
Example23_5.cs illustrates the use of a DataView object to
filter and sort rows
*/

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

public class Example23_5
{

public static void Main()
{

// formulate a string containing the details of the
// database connection
string connectionString =
“server=localhost;database=Northwind;uid=sa;pwd=sa”;

// create a SqlConnection object to connect to the
// database, passing the connection string to the constructor
SqlConnection mySqlConnection =
new SqlConnection(connectionString);

// formulate a string containing a SELECT statement
string selectString =
“SELECT CustomerID, CompanyName, City, Country ” +
“FROM Customers”;

// create a SqlCommand object to hold the SELECT statement
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

// set the CommandText property of the SqlCommand object to
// the SELECT string
mySqlCommand.CommandText = selectString;

// create a SqlDataAdapter object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

// set the SelectCommand property of the SqlAdapter object
// to the SqlCommand object
mySqlDataAdapter.SelectCommand = mySqlCommand;

// create a DataSet object to store the results of
// the SELECT statement
DataSet myDataSet = new DataSet();

// open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open();

// use the Fill() method of the SqlDataAdapter object to
// retrieve the rows from the table, storing the rows locally
// in a DataTable of the DataSet object
Console.WriteLine(“Retrieving rows from the Customers table”);
mySqlDataAdapter.Fill(myDataSet, “Customers”);

// create a DataView object
DataView myDataView =
new DataView(myDataSet.Tables[“Customers”]);

// set the RowFilter property of the DataView object
myDataView.RowFilter = “Country = 'UK'”;

// set the Sort property of the DataView object
myDataView.Sort = “CustomerID ASC”;

// display the rows in the DataView object
foreach (DataRowView myDataRowView in myDataView)
{
for (int count = 0; count < myDataView.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } } // close the database connection using the Close() method // of the SqlConnection object mySqlConnection.Close(); } } [/csharp]

Map table and column names

   


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

class Mappings
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText = "SELECT ID AS MappedID, FirstName, LastName " +
      "FROM Employee AS Emp " +
      "WHERE ID = 9";
    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();
    mySqlConnection.Open();
    mySqlDataAdapter.Fill(myDataSet, "Employee");
    mySqlConnection.Close();

    DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employee", "Emp");

    myDataSet.Tables["Employee"].TableName = "Emp";

    Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable);
    Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);

    myDataTableMapping.ColumnMappings.Add("ID", "MappedID");

    DataTable myDataTable = myDataSet.Tables["Emp"];
    foreach (DataRow myDataRow in myDataTable.Rows)
    {
      Console.WriteLine("ID = " + myDataRow["MappedID"]);
      Console.WriteLine("FirstName = " + myDataRow["FirstName"]);
      Console.WriteLine("LastName = " + myDataRow["LastName"]);
    }
  }
}