申请

申请

导航

Today Read

Tow methods,IDataReader/IDataReader,to access database
IDataReader:
System.Data.SqlClient.SqlDataReader
System.Data.OleDb.OleDb.OleDataReader
System.Data.Odbc
System.Data.OracleClient
IDbConnection:
SqlConnection/OleDbConnection each one has a ConnectionString
IDbCommand:
IDbCommand.ExecuteNonQuery(),is used to execute SQL command that
does not return any data.
IDbCommand.ExecuteScalar()
IDbCommand.ExecuteReader()


DataSet
DataSet.DataTableCollection
DataSet.DataRelateCollection
DataSet.DataColumnCollection
DataSet.DataRowCollection
DataSet.DataRelation
DataSet.Constraint

IDbDataAdapter to map a DataSet to a database

XmlSchema schema=XmlSchema.Read(
 new FileStream("Coupons.xsd",FileMode.Open),null);
XmlValidatingReader reader=new XmlValidatingReader(
 new XmlTextReaDER("Coupons.xml"));
reader.Schemas.Add(schema);
reader.ValidationType=ValidationType.Schema;
while (reader.Read()){
 //this will throw an exception if invalid
}

DataSet
<!--Creating a DataSet for database-->
using System;
using System.Data;

public class CreateDataSet {
  public static void Main(string [ ] args) {

    DataSet dataSet = new DataSet("AngusHardware");

    DataTable customers = dataSet.Tables.Add("customers");
    DataColumn customersCustomerId = customers.Columns.Add("customer_id",
      typeof(long));
    customers.Columns.Add("name",typeof(string)).AllowDBNull = false;
    customers.Columns.Add("address1",typeof(string)).AllowDBNull = false;
    customers.Columns.Add("address2",typeof(string));
    customers.Columns.Add("address3",typeof(string));
    customers.Columns.Add("city",typeof(string)).AllowDBNull = false;
    customers.Columns.Add("state",typeof(string)).AllowDBNull = false;
    customers.Columns.Add("zip",typeof(string)).AllowDBNull = false;
    customers.PrimaryKey = new DataColumn [ ] {customersCustomerId};

    DataTable coupons = dataSet.Tables.Add("coupons");
    DataColumn couponCouponCode = coupons.Columns.Add("coupon_code",  
      typeof(string));
    coupons.Columns.Add("discount_amount",
      typeof(Double)).AllowDBNull = false;
    coupons.Columns.Add("discount_type", typeof(int)).AllowDBNull = false;
    coupons.Columns.Add("expiration_date",
      typeof(DateTime)).AllowDBNull = false;
    coupons.PrimaryKey = new DataColumn [ ] {couponCouponCode};

    DataTable couponRedemptions =
      dataSet.Tables.Add("coupon_redemptions");
    DataColumn couponRedemptionsCouponCode =
      couponRedemptions.Columns.Add("coupon_code", typeof(string));
    couponRedemptions.Columns.Add("total_discount",
      typeof(Double)).AllowDBNull = false;
    couponRedemptions.Columns.Add("redemption_date",
      typeof(DateTime)).AllowDBNull = false;
    DataColumn couponRedemptionsCustomerId =
      couponRedemptions.Columns.Add("customer_id", typeof(long));

    dataSet.Relations.Add(couponCouponCode, couponRedemptionsCouponCode);
    dataSet.Relations.Add(customersCustomerId,
      couponRedemptionsCustomerId);

    dataSet.WriteXmlSchema("Coupons.xsd");
  }
}
<!--End Creating a DataSet for database-->
"xsd /dataset Coupons.xsd" this command will generate Coupons.cs

<!--Populating a DataSet-->
using System;
using System.Data;

public class CreateData {
  public static void Main(string [ ] args) {
    DataSet dataSet = new DataSet( );
    dataSet.ReadXmlSchema("Coupons.xsd");
   
    DataTable couponsTable = dataSet.Tables["coupons"];

    DataRow couponRow = couponsTable.NewRow( );
    couponRow["coupon_code"] = "763FF";
    couponRow["discount_amount"] = 0.5;
    couponRow["discount_type"] = DiscountType.Fixed;
    couponRow["expiration_date"] = new DateTime(2002,12,31);
    couponsTable.Rows.Add(couponRow);

    dataSet.WriteXml("Coupons.xml");
  }
}

<!--End Populating a DataSet-->

<!--Connection a DataSet to the Database-->
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;

public class FillDataSet {
 
  public static void Main(string [ ] args) {
   
    SqlConnection connection = new SqlConnection(
      "Initial Catalog=AngusHardware; User ID=sa");
    SqlDataAdapter adapter = new SqlDataAdapter( );
    AngusHardware dataSet = new AngusHardware( );
   
    adapter.SelectCommand = new SqlCommand("SELECT coupon_code, " +
      "discount_amount, discount_type, expiration_date FROM coupons",
      connection);

    adapter.UpdateCommand = new SqlCommand(
      "UPDATE coupons SET coupon_code = @couponCode, discount_amount = " +
      "@discountAmount, discount_type = @discountType, expiration_date = " +
      "@expirationDate WHERE coupon_code = @couponCode", connection);
    adapter.UpdateCommand.Parameters.Add("@couponCode",
      SqlDbType.Char,10,"coupon_code");
    adapter.UpdateCommand.Parameters.Add("@discountAmount",
      SqlDbType.Float,8,"discount_amount");
    adapter.UpdateCommand.Parameters.Add("@discountType",
      SqlDbType.TinyInt,1,"discount_type");
    adapter.UpdateCommand.Parameters.Add("@expirationDate",
      SqlDbType.DateTime,8,"expiration_date");

    adapter.Fill(dataSet, "coupons");

    dataSet.coupons[0].expiration_date = DateTime.Now;

    adapter.Update(dataSet, "coupons");
  }
}
<!--End Connection a DataSet to the Database-->

<!--Tracking changes to a DataSet--->
add this line before the Update() statement
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr=
"urn:schemas-microsoft-com:xml-diffgram-v1">
  <AngusHardware>
    <coupons diffgr:id="coupons1" msdata:rowOrder="0" diffgr:hasChanges="modified">
      <coupon_code>077GH     </coupon_code>
      <discount_amount>15</discount_amount>
      <discount_type>0</discount_type>
      <expiration_date>2002-11-09T14:17:41.6372544-05:00</expiration_date>
    </coupons>
    <coupons diffgr:id="coupons2" msdata:rowOrder="1">
      <coupon_code>665RQ     </coupon_code>
      <discount_amount>15</discount_amount>
      <discount_type>0</discount_type>
      <expiration_date>2002-11-30T00:00:00.0000000-05:00</expiration_date>
    </coupons>
    <coupons diffgr:id="coupons3" msdata:rowOrder="2">
      <coupon_code>81BIN     </coupon_code>
      <discount_amount>10</discount_amount>
      <discount_type>1</discount_type>
      <expiration_date>2003-01-31T00:00:00.0000000-05:00</expiration_date>
    </coupons>
    <coupons diffgr:id="coupons4" msdata:rowOrder="3">
      <coupon_code>99GGY     </coupon_code>
      <discount_amount>5</discount_amount>
      <discount_type>0</discount_type>
      <expiration_date>2002-12-31T00:00:00.0000000-05:00</expiration_date>
    </coupons>
  </AngusHardware>
  <diffgr:before>
    <coupons diffgr:id="coupons1" msdata:rowOrder="0">
      <coupon_code>077GH     </coupon_code>
      <discount_amount>15</discount_amount>
      <discount_type>0</discount_type>
      <expiration_date>2002-11-09T14:01:24.1830000-05:00</expiration_date>
    </coupons>
  </diffgr:before>
</diffgr:diffgram>

<!--End Tracking changes to a DataSet--->

Reading XML from a database
<!--Reading XML Data Directly-->
ExecuteXmlReader() is a method of SqlCommand and not OleDbCommand
using System;
using System.Data.SqlClient;
using System.Xml;

public class ReadDataAsXml {
  public static void Main(string [ ] args) {
    string command = "SELECT name, expiration_date, total_discount " +
      "FROM coupons, coupon_redemptions, customers " +
      "WHERE coupons.coupon_code = coupon_redemptions.coupon_code " +
      "AND coupon_redemptions.customer_id = customers.customer_id " +
      "FOR XML AUTO";

    SqlCommand xmlCommand = new SqlCommand(command, connection);

    connection.Open( );
    XmlReader reader = xmlCommand.ExecuteXmlReader( );

    XmlDocument doc = new XmlDocument( );
    doc.Load(reader);
    doc.Save(Console.Out);

    connection.Close( );
  }
}
<!--End Reading XML Data Directly-->

<!--Reading Data into a DOM Tree-->
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

public class ReadDataAsXml {
  public static void Main(string [ ] args) {
   
    DataSet dataSet = new DataSet("AngusHardware");
   
    SqlConnection connection = new SqlConnection(
      "Initial Catalog=AngusHardware; User ID=sa");
   
    string command = "SELECT name, redemption_date, total_discount " +
      "FROM coupon_redemptions a, customers b " +
      "WHERE a.customer_id = b.customer_id";
    SqlDataAdapter adapter = new SqlDataAdapter(command, connection);
   
    adapter.Fill(dataSet, "CouponsRedeemed");

    XmlDataDocument doc = new XmlDataDocument(dataSet);  

    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;
    doc.WriteTo(writer);
  }
}
<!--End Reading Data into a DOM Tree-->
database of xml could have two representation HierarChilcal/Relation
There a couple of ways to present DataSet as hierarchilcal XML view
transformation and synchronizing data
<!--programe to transform a DataSet to annother XML format-->
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Xsl;

public class TransformData {
  public static void Main(string [ ] args) {
   
    DataSet dataSet = new DataSet("AngusHardware");
   
    SqlConnection connection = new SqlConnection(
      "Initial Catalog=AngusHardware; Integrated Security=SSPI; User ID=sa");
   
    SqlDataAdapter customersAdapter = new SqlDataAdapter(
      "SELECT * FROM customers", connection);
    SqlDataAdapter couponsAdapter = new SqlDataAdapter(
      "SELECT * FROM coupons", connection);
    SqlDataAdapter couponRedemptionsAdapter = new SqlDataAdapter(
      "SELECT * FROM coupon_redemptions", connection);
   
    customersAdapter.Fill(dataSet, "customers");
    couponsAdapter.Fill(dataSet, "coupons");
    couponRedemptionsAdapter.Fill(dataSet, "coupon_redemptions");

    XmlDataDocument doc = new XmlDataDocument(dataSet);
   
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;
   
    XslTransform transform = new XslTransform( );
    transform.Load("Coupons.xsl");
    transform.Transform(doc, null, writer);
  }
}
<!--Realte xslt-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" />
 
  <xsl:template match="/">
    <xsl:apply-templates select="AngusHardware" />
  </xsl:template>
 
  <xsl:template match="AngusHardware">
    <AngusHardware>
      <xsl:apply-templates select="customers" />
      <xsl:apply-templates select="coupons" />
    </AngusHardware>
  </xsl:template>
 
  <xsl:template match="customers">
    <xsl:copy-of select="." />
  </xsl:template>
 
  <xsl:template match="coupons">
    <coupons>
      <xsl:copy-of select="./coupon_code" />
      <xsl:copy-of select="./discount_amount" />
      <xsl:copy-of select="./discount_type" />
      <xsl:copy-of select="./expiration_date" />
      <xsl:variable name="coupon_code" select="./coupon_code" />
      <xsl:if test="count(//coupon_redemptions[coupon_code=$coupon_code]) > 0">
        <xsl:for-each select="//coupon_redemptions[coupon_code=$coupon_code]">
          <xsl:copy-of select="." />
        </xsl:for-each>
      </xsl:if>
    </coupons>
  </xsl:template>
 
</xsl:stylesheet>

<!--End Realte xslt-->
<!--End programe to transform a DataSet to annother XML format-->

<!--Synchronizing Data-->
AngusHardware dataSet = new AngusHardware( );
XmlDataDocument doc = new XmlDataDocument(dataSet);
doc.Load("HierarchicalCoupons.xml");
XmlTextWriter writer = new XmlTextWriter(Console.Out);
writer.Formatting = Formatting.Indented;
//dataSet.WriteXml(writer);
//change to
doc.WriteTo(writer);
<!--End Synchronizing Data-->

(2)for using web services,hava five distinct steps:
choosing and implementing the web sevices provider,
describing the web service,
handling web service request,
creating web service clients,
publishing the web service

<!--SOPA request-->
POST /dotNetAndXml/InventoryQuery.asmx HTTP/1.1
Host: 127.0.0.1
Content-Type: text/xml; charset=utf-8
Content-Length: 365
SOAPAction: "http://angushardware.com/GetNumberInStock"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetNumberInStock xmlns="http://angushardware.com">
      <productCode>803B</productCode>
    </GetNumberInStock>
  </soap:Body>
</soap:Envelope>
<!--End SOPA request-->

<!--SOPA response-->
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: 400

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="
http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetNumberInStockResponse xmlns="http://angushardware.com">
      <GetNumberInStockResult>0</GetNumberInStockResult>
    </GetNumberInStockResponse>
  </soap:Body>
</soap:Envelope>
<!--End SOPA response-->
<!--Issuing an http request-->
using System;
using System.IO;
using System.Net;
using System.Xml.XPath;

public class GetNumberInStockHttpGet {

  public static void Main(string [ ] args) {
    WebRequest request = WebRequest.Create("http://127.0.0.1/dotNetAndXml
    /InventoryQuery.asmx/GetNumberInStock?productCode=803B");
    request.Method = "GET";

WebResponse response = request.GetResponse( );
    Stream stream = response.GetResponseStream( );

    XPathDocument document = new XPathDocument(stream);
    XPathNavigator nav = document.CreateNavigator( );

    XPathNodeIterator nodes = nav.Select("//int");
    Console.WriteLine(nodes.Current);
  }
}
<!--End issuing an http request-->
<!--Issuing an http post request-->
using System;
using System.IO;
using System.Net;

public class GetNumberInStockHttpPost {

  public static void Main(string [ ] args) {
    string content = "productCode=803B";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
      "http://127.0.0.1:80/dotNetAndXml/InventoryQuery.asmx/GetNumberInStock");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = content.Length;

    StreamWriter streamWriter =
      new StreamWriter(request.GetRequestStream( ));
    streamWriter.Write(content);
    streamWriter.Flush( );

    WebResponse response = request.GetResponse( );
    Stream stream = response.GetResponseStream( );

    XPathDocument document = new XPathDocument(stream);
    XPathNavigator nav = document.CreateNavigator( );

    XPathNodeIterator nodes = nav.Select("//int");
    Console.WriteLine(nodes.Current);
  }
}
<!--End ssuing an http post request-->

<!--Issuing a SOPA request-->
using System;
using System.IO;
using System.Net;
using System.Xml;

public class GetNumberInStockSoap {

  private const string soapNS =
    "http://schemas.xmlsoap.org/soap/envelope/";
  private static readonly encoding = Encoding.UTF8;

  public static void Main(string [ ] args) {
    MemoryStream stream = new MemoryStream( );
    XmlTextWriter writer = new XmlTextWriter(stream,encoding);

    writer.WriteStartDocument( );
    writer.WriteStartElement("soap","Envelope",soapNS);
    writer.WriteStartElement("Body",soapNS);
    writer.WriteStartElement("GetNumberInStock",angusNS);
    writer.WriteElementString("productCode","803B");
    writer.WriteEndElement( ); // GetNumberInStock
    writer.WriteEndElement( ); // soap:Body
    writer.WriteEndElement( ); // soap:Envelope
    writer.WriteEndDocument( );
    writer.Flush( );
    stream.Seek(0,SeekOrigin.Begin);
    StreamReader reader = new StreamReader(stream);
    string soap = reader.ReadToEnd( );

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
      "http://127.0.0.1/dotNetAndXml/InventoryQuery.asmx");
     
    request.Method = "POST";
    request.ContentType = "text/xml; charset=" + encoding.HeaderName;
    request.ContentLength = soap.Length;
    request.Headers["SOAPAction"] = "http://angushardware.com/InventoryQuery/
GetNumberInStock";

    StreamWriter streamWriter =
      new StreamWriter(request.GetRequestStream( ));
    streamWriter.Write(soap);
    streamWriter.Flush( );

    WebResponse response = request.GetResponse( );
    Stream responseStream = response.GetResponseStream( );
    XPathDocument document = new XPathDocument(responseStream);
    XPathNavigator nav = document.CreateNavigator( );
    XPathNodeIterator nodes =
      nav.Select("//Envelope/Body/GetNumberInStockResponse/GetNumberInStockResult");
    Console.WriteLine(nodes.Current);
  }
}

<!--End issuing a SOPA request-->


 

posted on 2005-08-01 09:38  billfang  阅读(504)  评论(0)    收藏  举报