Csharp/C Sharp by API/System.Data/DataSet

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

DataSet.Delete

  
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
class Program {
    static void Main(string[] args) {
        DataSet theCarsInventory = new DataSet();
        SqlConnection cn = new SqlConnection("server=(local);User ID=sa;Pwd=;database=Cars");
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Inventory", cn);
        SqlCommandBuilder invBuilder = new SqlCommandBuilder(da);
        da.Fill(theCarsInventory, "Inventory");
        PrintDataSet(theCarsInventory);
        try {
            theCarsInventory.Tables["Inventory"].Rows[1].Delete();
            da.Update(theCarsInventory, "Inventory");
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
        theCarsInventory = new DataSet();
        da.Fill(theCarsInventory, "Inventory");
        PrintDataSet(theCarsInventory);
    }
    static void PrintDataSet(DataSet ds) {
        Console.WriteLine("Tables in "{0}" DataSet.\n", ds.DataSetName);
        foreach (DataTable dt in ds.Tables) {
            Console.WriteLine("{0} Table.\n", dt.TableName);
            for (int curCol = 0; curCol < dt.Columns.Count; curCol++) {
                Console.Write(dt.Columns[curCol].ColumnName.Trim() + "\t");
            }
            for (int curRow = 0; curRow < dt.Rows.Count; curRow++) {
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++) {
                    Console.Write(dt.Rows[curRow][curCol].ToString().Trim() + "\t");
                }
                Console.WriteLine();
            }
        }
    }
}


DataSet.Merge

  
using System;
using System.Data;
using System.Data.SqlClient;
class Merge
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.rumandText =
      "SELECT ID, FirstName, LastName, Address " +
      "FROM Customers " +
      "WHERE ID IN ("001", "002", "003")";
    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();
    mySqlConnection.Open();
    mySqlDataAdapter.Fill(myDataSet, "Customers");
    mySqlCommand.rumandText =
      "SELECT ID, FirstName, LastName, Address " +
      "FROM Customers " +
      "WHERE CustomerID IN ("008", "009")";
    DataSet myDataSet2 = new DataSet();
    mySqlDataAdapter.Fill(myDataSet2, "Customers2");
    mySqlCommand.rumandText =
      "SELECT TOP 5 ProductID, ProductName, UnitPrice " +
      "FROM Products " +
      "ORDER BY ProductID";
    DataSet myDataSet3 = new DataSet();
    mySqlDataAdapter.Fill(myDataSet3, "Products");
    mySqlConnection.Close();
    myDataSet.Merge(myDataSet2);
    myDataSet.Merge(myDataSet3, true, MissingSchemaAction.Add);
    foreach (DataTable myDataTable in myDataSet.Tables) {
      Console.WriteLine("\nReading from the " + myDataTable + "DataTable");
      foreach (DataRow myDataRow in myDataTable.Rows) {
        foreach (DataColumn myDataColumn in myDataTable.Columns) {
          Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]);
        }
      }
    }
  }
}


DataSet.MergeFailed

 
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
public class MainClass {
  public static void Main(){
    OleDbConnection conn = new OleDbConnection();
    string strDSN = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
    conn.ConnectionString = strDSN;
    conn.Open();
    string sql = "SELECT * FROM orders ";
    OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
    DataSet ds1 = new DataSet("ds1");
    da.Fill(ds1);
    sql = "SELECT * FROM Customers ";
    da = new OleDbDataAdapter(sql, conn);
    DataSet ds2 = new DataSet("ds2");
    da.Fill(ds2);
    ds1.MergeFailed += new MergeFailedEventHandler(OnMergeFailed);
    ds1.Merge(ds2);
  }
  protected static void OnMergeFailed  (object sender, MergeFailedEventArgs args)
  {
    MessageBox.Show(args.Conflict.ToString());
  }
}


DataSet.Read

  
using System;
using System.Data;            // Use ADO.NET namespace
using System.Data.SqlClient;  // Use SQL Server data provider namespace
using System.Collections.Generic;
using System.Text;
class Program {
    static void Main(string[] args) {
        SqlConnection thisConnection = new SqlConnection(
            @"Server=(local)\sqlexpress;Integrated Security=True;" +
          "Database=northwind");
        SqlDataAdapter thisAdapter = new SqlDataAdapter(
             "SELECT CustomerID, ContactName FROM Customers", thisConnection);
        DataSet thisDataSet = new DataSet();
        thisAdapter.Fill(thisDataSet, "Customers");
        foreach (DataRow theRow in thisDataSet.Tables["Customers"].Rows) {
            Console.WriteLine(theRow["CustomerID"] + "\t" +
                                                  theRow["ContactName"]);
        }
        thisConnection.Close();
    }
}


DataSet.ReadXml

  

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
class Program {
    static void Main(string[] args) {
        DataSet thisDataSet = new DataSet();
        thisDataSet.ReadXml("nwinddata.xml");
        foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows) {
            Console.WriteLine("Customer ID: " + custRow["CustomerID"] +
                              " Name: " + custRow["CompanyName"]);
        }
        Console.WriteLine("Table created by ReadXml is called {0}",
                           thisDataSet.Tables[0].TableName);
    }
}


DataSet.Relations.Add

  
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
public class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }
    private void getData_Click(object sender, EventArgs e) {
        string orders = "SELECT * FROM Orders";
        string customers = "SELECT * FROM Customers";
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwind"].ConnectionString)) {
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(customers, con);
            da.Fill(ds, "Customers");
            da = new SqlDataAdapter(orders, con);
            da.Fill(ds, "Orders");
            ds.Relations.Add("CustomerOrders",
                ds.Tables["Customers"].Columns["CustomerID"],
                ds.Tables["Orders"].Columns["CustomerID"]);
            dataGrid1.SetDataBinding(ds, "Customers");
        }
    }
    private void InitializeComponent() {
        this.getData = new System.Windows.Forms.Button();
        this.dataGrid1 = new System.Windows.Forms.DataGrid();
        ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
        this.SuspendLayout();
        this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.getData.Location = new System.Drawing.Point(316, 299);
        this.getData.Name = "getData";
        this.getData.Size = new System.Drawing.Size(75, 23);
        this.getData.TabIndex = 1;
        this.getData.Text = "Get Data";
        this.getData.UseVisualStyleBackColor = true;
        this.getData.Click += new System.EventHandler(this.getData_Click);
        this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.dataGrid1.DataMember = "";
        this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
        this.dataGrid1.Location = new System.Drawing.Point(12, 12);
        this.dataGrid1.Size = new System.Drawing.Size(379, 281);
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(403, 334);
        this.Controls.Add(this.dataGrid1);
        this.Controls.Add(this.getData);
        ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
        this.ResumeLayout(false);
    }
    private System.Windows.Forms.Button getData;
    private System.Windows.Forms.DataGrid dataGrid1;
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}


DataSet.Tables

  
using System;
using System.Data;
using System.Data.SqlClient;
class MultipleDataTables
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.rumandText =
      "SELECT TOP 2 ID, FirstName, LastName " +
      "FROM Employee " +
      "ORDER BY ID;" +
      "SELECT ID, LastName " +
      "FROM MyEmployee " +
      "WHERE ID = 9;";
    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();
    mySqlConnection.Open();
    int numberOfRows = mySqlDataAdapter.Fill(myDataSet);
    Console.WriteLine("numberOfRows = " + numberOfRows);
    mySqlConnection.Close();
    myDataSet.Tables["Table"].TableName = "Employee";
    myDataSet.Tables["Table1"].TableName = "MyEmployee";
    foreach (DataTable myDataTable in myDataSet.Tables) {
      Console.WriteLine("\nReading from the " +
        myDataTable.TableName + "DataTable");
      foreach (DataRow myDataRow in myDataTable.Rows)
      {
        foreach (DataColumn myDataColumn in myDataTable.Columns)
        {
          Console.WriteLine(myDataColumn + "= " +
            myDataRow[myDataColumn]);
        }
      }
    }
  }
}


DataSet.WriteXml

  
   
using System;
using System.Data;
using System.Data.SqlClient;
class WriteAndReadXML {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
        mySqlCommand.rumandText =
          "SELECT TOP 2 CustomerID, CompanyName, ContactName, " +
          "Address " +
          "FROM Customers " +
          "ORDER BY CustomerID";
        SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
        mySqlDataAdapter.SelectCommand = mySqlCommand;
        DataSet myDataSet = new DataSet();
        mySqlConnection.Open();
        mySqlDataAdapter.Fill(myDataSet, "Customers");
        mySqlConnection.Close();
        myDataSet.WriteXml("myXmlFile.xml");
        myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);
        myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");
        myDataSet.Clear();
        myDataSet.ReadXml("myXmlFile.xml");
        DataTable myDataTable = myDataSet.Tables["Customers"];
        foreach (DataRow myDataRow in myDataTable.Rows) {
            Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]);
            Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]);
            Console.WriteLine("ContactName = " + myDataRow["ContactName"]);
            Console.WriteLine("Address = " + myDataRow["Address"]);
        }
    }
}


new DataSet(String data)

   
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.Odbc;
public class MainClass : System.Windows.Forms.Form
{
  private System.Windows.Forms.DataGrid dataGrid1;
  public MainClass()
  {
    InitializeComponent();
  }
  private void InitializeComponent()
  {
    this.dataGrid1 = new System.Windows.Forms.DataGrid();
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
    this.SuspendLayout();
    // 
    // dataGrid1
    // 
    this.dataGrid1.DataMember = "";
    this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
    this.dataGrid1.Location = new System.Drawing.Point(0, 8);
    this.dataGrid1.Name = "dataGrid1";
    this.dataGrid1.Size = new System.Drawing.Size(376, 288);
    this.dataGrid1.TabIndex = 0;
    // 
    // MainClass
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(384, 302);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                    this.dataGrid1});
    this.Load += new System.EventHandler(this.MainClass_Load);
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new MainClass());
  }
  private void MainClass_Load(object sender, System.EventArgs e)
  {
    string connectionString = @"Driver={MySQL};SERVER=localhost;DATABASE=NorthwindMySQL;";
    OdbcConnection conn= new OdbcConnection(connectionString);
    conn.Open();
    OdbcDataAdapter da = new OdbcDataAdapter ("SELECT CustomerID, ContactName, ContactTitle FROM Customers", conn);            
    DataSet ds = new DataSet("Cust");     
    da.Fill(ds, "Customers");
    dataGrid1.DataSource = ds.DefaultViewManager;
    conn.Close();
  }
}