Populate a DataSet object using a SELECT statement : SqlCommand : Database C# Source Code


Custom Search

C# Source Code » Database » SqlCommand »

 

Populate a DataSet object using a SELECT statement








    
 

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

class PopulateDataSetUsingSelect {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
        mySqlCommand.CommandText =
          "SELECT TOP 5 ProductID, ProductName, UnitPrice " +
          "FROM Products " +
          "ORDER BY ProductID";
        SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
        mySqlDataAdapter.SelectCommand = mySqlCommand;
        DataSet myDataSet = new DataSet();
        mySqlConnection.Open();
        Console.WriteLine("Retrieving rows from the Products table");
        int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products");
        Console.WriteLine("numberOfRows = " + numberOfRows);
        mySqlConnection.Close();
        DataTable myDataTable = myDataSet.Tables["Products"];
        foreach (DataRow myDataRow in myDataTable.Rows) {
            Console.WriteLine("ProductID = " + myDataRow["ProductID"]);
            Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
            Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
        }
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Database
» SqlCommand