您的位置:首页 > 数据库

DO.NET在开发中的部分使用方法和技巧

2009-10-26 13:38 316 查看
using System.Data; using System.Data.SqlClient; public DataTable RetrieveRowsWithDataTable() { using ( SqlConnection conn = new SqlConnection(connectionString) ) { conn.Open(); SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter adapter = new SqlDataAdapter( cmd ); DataTable dataTable = new DataTable("Products"); adapter .Fill(dataTable); return dataTable; } } 

使用 SqlAdapter 生成 DataSet 或 DataTable 

 

1.创建一个 SqlCommand 对象以调用该存储过程,并将其与一个 SqlConnection 对象(显示)或连接字符串(不显示)相关联。

2.创建一个新的 SqlDataAdapter 对象并将其与 SqlCommand 对象相关联。 

3.创建一个 DataTable(也可以创建一个 DataSet)对象。使用构造函数参数来命名 DataTable。 

4.调用 SqlDataAdapter 对象的 Fill 方法,用检索到的行填充 DataSet 或 DataTable。 

 

如何使用 SqlDataReader 来检索多个行

以下代码片段阐明了可检索多个行的 SqlDataReader方法。

using System.IO; 

using System.Data; 

using System.Data.SqlClient; 

public SqlDataReader RetrieveRowsWithDataReader() 

{ SqlConnection conn = new SqlConnection( "server=(local);Integrated Security=SSPI;database=northwind"); 

SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn ); 

cmd.CommandType = CommandType.StoredProcedure; 

try { conn.Open();

// Generate the reader. CommandBehavior.CloseConnection causes the // the connection to be closed when the reader object is closed 

return( cmd.ExecuteReader( CommandBehavior.CloseConnection ) ); } 

catch { conn.Close(); throw; } } // Display the product list using the console 

private void DisplayProducts() { SqlDataReader reader = RetrieveRowsWithDataReader(); 

try { while (reader.Read()) { Console.WriteLine("{0} {1} {2}", reader.GetInt32(0).ToString(), reader.GetString(1) ); } }

finally { reader.Close(); // Also closes the connection due to the // CommandBehavior enum used when generating the reader } } 

使用 SqlDataReader 检索行 

 

1.创建一个用来执行存储过程的 SqlCommand 对象,并将其与一个 SqlConnection对象相关联。 

2.打开连接。 

3.通过调用 SqlCommand 对象的 ExecuteReader方法创建一个 SqlDataReader对象。 

 

4.

 要从流中读取数据,请调用 SqlDataReader对象的 Read方法来检索行,并使用类型化访问器方法(如 GetInt32和 GetString方法)来检索列值。 

 

5.

 使用完读取器后,请调用其 Close方法。

 

 

如何使用 XmlReader 检索多个行

可以使用 SqlCommand对象来生成 XmlReader对象,后者可提供对 XML 数据的基于流的只进访问。命令(通常为存储过程)必
须产生基于 XML 的结果集,对于 SQL Server 2000 而言,该结果集通常包含一个带有有效 FOR XML子句的 SELECT语句。
以下代码片段阐明了该方法:

public void RetrieveAndDisplayRowsWithXmlReader() { 

using( SqlConnection conn = new SqlConnection(connectionString) ) 

{; SqlCommand cmd = new SqlCommand("DATRetrieveProductsXML", conn ); 

cmd.CommandType = CommandType.StoredProcedure;

try { conn.Open(); 

XmlTextReader xreader = (XmlTextReader)cmd.ExecuteXmlReader(); 

while ( xreader.Read() ) { if ( xreader.Name == "PRODUCTS" ) { string strOutput = xreader.GetAttribute("ProductID"); 

strOutput += " "; strOutput += xreader.GetAttribute("ProductName");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息