欢迎大家光临【无师自通-教程网】您的到来是我们的荣幸。本站提供photoshop教程,ps教程,flash教程,cad教程,网页制作教程,excel教程,asp教程,vb教程,3d教程,c语言教程,html教程,coreldraw教程,dreamweaver教程,java教程,3dmax教程 等各种教程为主题的内容和服务,相信您会在这里找到您所需要的东东。无师自通伴您一生-谢谢您的光临!!
网站地图 设为首页
简繁切换 加入收藏
栏目待定 留言本站
您现在的位置: 无师自通-教程网 >> WEB开发 >> ASP.NET教程 >> .NET Framework >> 教程正文

  没有公告

教程: ASP.NET教程-.NET Framework-.NET 数据访问架构指南(二) 更多...
教程: ASP.NET教程-.NET Framework-.NET 数据访问架构指南(二)

ank" class="keylink">AccessComponent : ServicedComponent
提供虚拟Construct方法的替换实现方案。该方法在对象语言构造程序之后调用。在COM目录中保存的结构字符串是该方法的唯一字符串。
public override void Construct( string constructString )
{
// Construct method is called next after constructor.
// The configured DSN is supplied as the single argument
}
通过Assembly key文件或Assembly key Name属性为该汇编提供一个强名字。任何用COM 服务注册的汇编必须有一个强名字。关于带有强名字汇编的更多信息,参考:http://msdn.microsoft.com/library/en-us/cpguide/html/cpconworkingwithstrongly- namedassemblies.Asp。
[assembly: AssemblyKeyFile("DataServices.snk")]
为支持动态注册,可以利用汇编层上的属性ApplicationName和Application Action分别指定用于保持汇编元素和应用程序动作类型的COM 应用程序的名字。关于汇编注册的更多信息,参考: http://msdn.microsoft.com/library/en-us/cpguide/html/cpconregisteringserviced components.asp。
// the ApplicationName attribute specifies the name of the
// COM Application which will hold assembly components
[assembly : ApplicationName("DataServices")]

// the ApplicationActivation.ActivationOption attribute specifies
// where assembly components are loaded on activation
// Library : components run in the creator's process
// Server : components run in a system process, dllhost.exe
[assembly: ApplicationActivation(ActivationOption.Library)]
下列代码段是一个叫做DataAccessComponent的服务组件,它利用COM 结构字符串来获得数据库连接字符串。

using System;
using System.EnterpriseServices;

// the ApplicationName attribute specifies the name of the
// COM Application which will hold assembly components
[assembly : ApplicationName("DataServices")]

// the ApplicationActivation.ActivationOption attribute specifies
// where assembly components are loaded on activation
// Library : components run in the creator's process
// Server : components run in a system process, dllhost.exe
[assembly: ApplicationActivation(ActivationOption.Library)]

// Sign the assembly. The snk key file is created using the
// sn.exe utility
[assembly: AssemblyKeyFile("DataServices.snk")]

[ConstructionEnabled(Default="Default DSN")]
public class DataAccessComponent : ServicedComponent
{
private string connectionString;
public DataAccessComponent()
{
// constructor is called on instance creation
}
public override void Construct( string constructString )
{
// Construct method is called next after constructor.
// The configured DSN is supplied as the single argument
this.connectionString = constructString;
}
}
如何利用SqlDataAdapter来检索多个行

下面的代码说明如何利用SqlDataAdapter对象发出一个生成Data Set或Datatable的命令。它从SQL Server Northwind数据库中检索一系列产品目录。

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

public DataTable RetrieveRowsWithDataTable()
{
using ( SqlConnection conn = new SqlConnection(connectionString) )
{
SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter( cmd );
DataTable dt = new DataTable("Products");
da.Fill(dt);
return dt;
}
}
按下列步骤利用SqlAdapter生成DataSet或DataTable:

创建SqlCommand对象启用存储过程,并把它与SqlConnection对象(显示的)或连接字符串(未显示)相联系。
创建一个新的SqlDataAdapter对象,并把它SqlCommand对象相联系。
创建DataTable(或者DataSet)对象。利用构造程序自变量命名DataTable.
调用SqlData Adapter对象的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();
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0).ToString(),
reader.GetString(1) );
}
reader.Close(); // Also closes the connection due to the
// CommandBehavior enum used when generating the reader
}
按下列步骤利用SqlDataReader检索多行:

创建用于执行存储的过程的SqlCommand对象,并把它与SqlConnection对象相联系。
打开链接。
通过调用SqlCommand对象的Excute Reader方法生成SqlDataReader对象。
从流中读取数据,调用SqlDataReader对象的Read方法来检索行,并利用分类的存取程序方法(如GetIut 32和Get String方法)检索列的值。
完成读取后,调用Close方法。
如何利用XmlReader检索多个行

可以利用SqlCommand对象生成XmlReader对象,它提供对XML数据的基于流的前向访问。该命令(通常是一个存储的过程)必须生成一个基于XML的结果设置,它对于SQL Server2000通常是由带有有效条款FOR XML的SELECT状态组成。下列代码段说明了这种方法:

public void RetrieveAndDisplayRowsWithXmlReader()
{
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");
Console.WriteLine( strOutput );
}
}
xreader.Close();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
上述代码使用了下列存储过程:

CREATE PROCEDURE DATRetrieveProductsXML
AS
SELECT * FROM PRODUCTS
FOR XML AUTO
GO
按下列步骤检索XML数据:

创建SqlCommand对象启用生成XML结果设置的过程。(比如,利用SELECT状态中的FOR XML条款)。把SqlCommand对象与一个链接相联系。
调用SqlCommand对象的ExecuteXmlReader方法,并把结果分配给前向对象XmlTextReader。当不需要任何返回数据的基于XML的验证时,这是应该使用的最快类型的XmlReader对象。
利用XmlTextReader对象的Read方法读取数据。
如何利用存储过程输出参数检索单个行

可以调用一个存储过程,它通过一种称做输出参数的方式可以在单个行中返回检索数据项。下列代码段利用存储的过程检索产品的名称和单价,该产品包含在Northwind数据库中。

void GetProductDetails( int ProductID,
out string ProductName, out decimal UnitPrice )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=Northwind");

// Set up the command object used to execute the stored proc
SqlCommand cmd = new SqlCommand( "DATGetProductDetailsSPOutput", conn );
cmd.CommandType = CommandType.StoredProcedure;
// Establish stored proc parameters.
// @ProductID int INPUT
// @ProductName nvarchar(40) OUTPUT
// @UnitPrice money OUTPUT

// Must explicitly set the direction of output parameters
SqlParameter paramProdID =
cmd.Parameters.Add( "@ProductID", ProductID );
paramProdID.Direction = ParameterDirection.Input;
SqlParameter paramProdName =
cmd.Parameters.Add( "@ProductName", SqlDbType.VarChar, 40 );
paramProdName.Direction = ParameterDirection.Output;
SqlParameter paramUnitPrice =
cmd.Parameters.Add( "@UnitPrice", SqlDbType.Money );
paramUnitPrice.Direction = ParameterDirection.Output;
try
{
conn.Open();
// Use ExecuteNonQuery to run the command.
// Although no rows are returned any mapped output parameters
// (and potentially return values) are populated
cmd.ExecuteNonQuery( );
// Return output parameters from stored proc
ProductName = paramProdName.Value.ToString();
UnitPrice = (decimal)paramUnitPrice.Value;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
按下列步骤利用存储的过程输出参数检索单个行:

创建一个SqlCommand对象,并把它与SqlConnection对象相联系。
通过调用SqlCommand’s Parameters集合的Add方法设置存储过程参数。缺省情况下,参数假定为输出参数,所以必须明确设置任何输出参数的方向。
注意 明确设置所有参数的方向是一次很好的练习,包括输入参数。

打开连接。
调用Sqlcommand对象的ExecuteNonQuery方法。它在输出参数(并潜在地带有一个返回值)中。
利用Value属性从合适的SqlParameter对象中检索输出参数。
关闭连接。
上述代码段启用了下列存储过程。

CREATE PROCEDURE DATGetProductDetailsSPOutput
@ProductID int,
@ProductName nvarchar(40) OUTPUT,
@UnitPrice money OUTPUT
AS
SELECT @ProductName = ProductName,
@UnitPrice = UnitPrice
FROM Products
WHERE ProductID = @ProductID
GO
如何利用SqlDataReader检索单个行

可以利用SqlDataReader对象检索单个行,以及来自返回数据流的所需栏的值。这由下列代码说明:

void GetProductDetailsUsingReader( int ProductID,
out string ProductName, out decimal UnitPrice )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=Northwind");

// Set up the command object used to execute the stored proc
SqlCommand cmd = new SqlCommand( "DATGetProductDetailsReader", conn );
cmd.CommandType = CommandType.StoredProcedure;
// Establish stored proc parameters.
// @ProductID int INPUT

SqlParameter paramProdID = cmd.Parameters.Add( "@ProductID", ProductID );
paramProdID.Direction = ParameterDirection.Input;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read(); // Advance to the one and only row

// Return output parameters from returned data stream
ProductName = reader.GetString(0);
UnitPrice = reader.GetDecimal(1);
reader.Close();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
按下列步骤返回带有SqlDataReader对象:

建立SqlCommand对象。
打开连接。
调用SqlDReader对象的ExecuteReader对象。
利用SqlDataReader对象的分类的存取程序方法检索输出参数--在这里是GetString和GetDecimal.
上述代码段启用了下列存储过程:

CREATE PROCEDURE DATGetProductDetailsReader
@ProductID int
AS
SELECT ProductName, UnitPrice FROM Products
WHERE ProductID = @ProductID
GO
如何利用ExecuteScalar单个项

ExecuteScalar方法是设计成用于返回单个值的访问。在返回多列或多行的访问事件中,ExecuteScalar只返回第一行的第一例。

下列代码说明如何查询某个产品ID的产品名称:

void GetProductNameExecuteScalar( int ProductID, out string ProductName )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommand("LookupProductNameScalar", conn );
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@ProductID", ProductID );
try
{
conn.Open();
ProductName = (string)cmd.ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
按下列步骤利用Execute Scalar检索单个项:

建立调用存储过程的SqlCommand对象。
打开链接。
调用ExecuteScalar方法,注意该方法返回对象类型。它包含检索的第一列的值,并且必须设计成合适的类型。
关闭链接。
上述代码启用了下列存储过程:

CREATE PROCEDURE LookupProductNameScalar
@ProductID int
AS
SELECT TOP 1 ProductName
FROM Products
WHERE ProductID = @ProductID
GO
如何利用存储过程输出或返回的参数检索单个项

利用存储过程输出或返回的参数可以查询单个值,下列代码说明了输出参数的使用:

void GetProductNameUsingSPOutput( int ProductID, out string ProductName )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommand("LookupProductNameSPOutput", conn );
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter paramProdID = cmd.Parameters.Add("@ProductID", ProductID );
ParamProdID.Direction = ParameterDirection.Input;

[4] [5] [6] [7] [8] [9] [10]

上一页  [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一页

教程录入:admin    责任编辑:admin 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
     
     
     
     

    asp连接mysql数据库

    asp连接mysql数据库-2

    frontpage2000教程---制作主页
    免责声明!本站资料大部分来自于互联网,其版权归原作者或其他合法者所有.如内容涉及或侵犯了您的权益,请通知本人,我将尽快处理!.欢迎您的光临。
    辽ICP备07003958号
    无师自通,伴你一生-教程网