Home Database Mysql Tutorial 黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc

黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc

Jun 07, 2016 pm 03:43 PM
enterprise microsoft

企业库数据库访问模块通过抽象工厂模式 , 允许用户通过简单的配置选择不同的数据库作为程序的数据源 , 大大解决了切换数据库时带来的麻烦 . 因为我本机只安装了 SQL Server 2005, 所以在此只做 SQL 的演示 , 需要深究的朋友可以访问以下网站 : http://msdn.m

企业库数据库访问模块通过抽象工厂模式,允许用户通过简单的配置选择不同的数据库作为程序的数据源,大大解决了切换数据库时带来的麻烦.因为我本机只安装了SQL Server 2005,所以在此只做SQL的演示,需要深究的朋友可以访问以下网站:

http://msdn.microsoft.com/en-us/library/ff664408%28v=PandP.50%29.aspx

 

企业库数据库访问模块的几大功能:

1.        最简单的功能,通过ExecuteNonQuery.方法执行SQL语句.

2.        执行ExecuteDataSet,返回DataSet类型的数据集.

3.        执行ExecuteScalar,获取返回的第一行第一列的信息.

4.        执行存储过程.

5.        通过代码实现事务.

6.        通过DataSet更新数据库.

7.        返回值XML.

8.       将返回的数据对象化.

9.       异步访问数据库.


以上的功能我会在下面一一介绍
,测试程序我已打包,大家可以点击这里下载.

 

下面介绍如何使用Microsoft Enterprise Library 5.0中的数据库访问模块.

1.   首先创建一个测试数据库,创建数据库的SQL文件我打包在压缩包里了,大家可以点击上面的下载链接下载.执行完SQL文件后,可以看到我们创建好的TestDB数据库:

黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc

2.   下载安装好MicrosoftEnterprise Library 5.0,然后在运行EntLibConfig.exe,选择Blocks菜单 ,单击 AddDatabase Settings .

黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc

 

3.    配置好文件之后保存为App.config文件,并添加到创建好的应用程序中.并添加相应的引用,在此我不再多讲,大家下载我打包好的程序运行即可看到

 黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc

4.      下面来介绍我在应用程序中实现的各个功能:

(1)     通过ExecuteNonQuery.方法执行SQL语句:      

///


/// 执行ExecuteNonQuery
///
privatevoid ExecuteNonQuery_Click(object sender, EventArgs e)
{
db.ExecuteNonQuery(CommandType.Text,
"INSERT INTO [College] ([CollegeID],[Name]) values (6,'体育学院')");
}

   

(2)    执行ExecuteDataSet,返回DataSet类型的数据集.

///


/// 执行ExecuteDataSet,返回College列表
///
///
privatevoid ExecuteDataSet_Click(object sender, EventArgs e)
{
string sql ="select * from College";
DbCommand dw
= db.GetSqlStringCommand(sql);

dataGridView1.DataSource
= db.ExecuteDataSet(dw).Tables[0];
}

 

 

(3)    执行ExecuteScalar,返回第一行第一列的值.

///


/// 执行ExecuteScalar,返回第一行第一列的值
///
///
privatevoid ExecuteScalar_Click(object sender, EventArgs e)
{
Database db
= DatabaseFactory.CreateDatabase("ConnectionString");

string sql ="select [Name] from College where [CollegeID] = 1";
DbCommand dc
= db.GetSqlStringCommand(sql);
string str ="获取的学院名称为:"+ (string)db.ExecuteScalar(dc);
MessageBox.Show(str);

sql
="select [CollegeID] from College where [CollegeID] = 1";
dc
= db.GetSqlStringCommand(sql);
str
="获取的学院ID为:"+ (int)db.ExecuteScalar(dc);
MessageBox.Show(str);
}

 

(4)    执行存储过程.

///


/// 执行存储过程
///
privatevoid StoredProcCommand_Click(object sender, EventArgs e)
{
DbCommand dc
= db.GetStoredProcCommand("usp_College_LoadByID");

db.AddInParameter(dc,
"@CollegeID", System.Data.DbType.Int32, 5);

dataGridView1.DataSource
= db.ExecuteDataSet(dc).Tables[0];
}

 

(5)    通过代码实现事务.

///


/// 事务
///
privatevoid Transaction_Click(object sender, EventArgs e)
{
DbCommand dc1
= db.GetStoredProcCommand("usp_College_Insert");

db.AddInParameter(dc1,
"@CollegeID", DbType.Int32, 7);
db.AddInParameter(dc1,
"@Name", DbType.String, "文旅学院");

DbCommand dc2
= db.GetStoredProcCommand("usp_College_Insert");

db.AddInParameter(dc2,
"@CollegeID", DbType.Int32, 7);
db.AddInParameter(dc2,
"@Name", DbType.String, "化工学院");

using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans
= conn.BeginTransaction();

try
{
//添加一个ID为7的学院
db.ExecuteNonQuery(dc1, trans);

//添加一个ID为7的学院,主键重复,事务将回滚
db.ExecuteNonQuery(dc2, trans);

//提交事务.
trans.Commit();
}
catch
{
//回滚
trans.Rollback();
}
conn.Close();
}

//查看数据库,数据未被添加,说明事务已回滚
ExecuteDataSet_Click(null, null);
}

 

(6)    通过DataSet更新数据库.

///


/// 通过DataSet更新数据库
///
privatevoid DataSetUpdate_Click(object sender, EventArgs e)
{
DataSet productsDataSet
=new DataSet();

string sql ="Select * From College";
DbCommand cmd
= db.GetSqlStringCommand(sql);

string CollegeTableName ="College";

//恢复原始数据
db.LoadDataSet(cmd, productsDataSet, CollegeTableName);

//获取数据表格
DataTable dTable = productsDataSet.Tables[CollegeTableName];

//添加一个新信息入DataSet中
DataRow addedRow = dTable.Rows.Add(newobject[] { 8, "外国语学院" });

//修改一个原有数据
dTable.Rows[0]["Name"] ="国教院";

//提供插入,更新,删除存储过程
DbCommand insertCommand = db.GetStoredProcCommand("usp_College_Insert");
db.AddInParameter(insertCommand,
"@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);
db.AddInParameter(insertCommand,
"@Name", DbType.String, "Name", DataRowVersion.Current);

DbCommand deleteCommand
= db.GetStoredProcCommand("usp_College_Delete");
db.AddInParameter(deleteCommand,
"@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);

DbCommand updateCommand
= db.GetStoredProcCommand("usp_College_Update");
db.AddInParameter(updateCommand,
"@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);
db.AddInParameter(updateCommand,
"@Name", DbType.String, "Name", DataRowVersion.Current);

//通过DataSet更新数据库
int rowsAffected = db.UpdateDataSet(productsDataSet, CollegeTableName, insertCommand, updateCommand, deleteCommand,
Microsoft.Practices.EnterpriseLibrary.Data.UpdateBehavior.Standard);

MessageBox.Show(
"影响的行数:"+ rowsAffected);
}

 

(7)    返回值XML化.

///


/// 返回值XML化
///
privatevoid ReturnXML_Click(object sender, EventArgs e)
{
//使用"FOR XML AUTO"参数使得SQL返回XML格式的信息
SqlDatabase sqldb = (SqlDatabase)DatabaseFactory.CreateDatabase("ConnectionString");

DbCommand cmd
= sqldb.GetSqlStringCommand("SELECT * FROM College FOR XML AUTO");
IEnumerable
string> productList;

using (var reader = sqldb.ExecuteXmlReader(cmd))
{
if (reader.IsStartElement())
{
var root
= (XElement)XNode.ReadFrom(reader);
productList
= root.Elements("CollegeID")
.Attributes(
"Name")
.Select(a
=> a.Value).ToArray();

MessageBox.Show(((XElement)root).ToString());
}
}
}

 

(8)    将返回的数据对象化.

///


/// DataAsObject
///
privatevoid DataAsObject_Click(object sender, EventArgs e)
{
//将返回的数据对象化
var results = db.ExecuteSprocAccessorCollege>("usp_College_LoadAll");

MessageBox.Show(results.ElementAt(
0).ToString());
}

 

 

(9)    异步访问数据库.

///


/// 异步访问数据库
///
privatevoid Async_Click(object sender, EventArgs e)
{
//创建新的数据库连接,属性必须添加:Asynchronous Processing=true
String connectionString =@"server=(local); database=TestDB; Integrated Security=true; Asynchronous Processing=true";
Database Sqldb
=new SqlDatabase(connectionString);
DbCommand cmd
= Sqldb.GetStoredProcCommand("usp_College_LoadbyID");
Sqldb.AddInParameter(cmd,
"@CollegeID", DbType.Int32, 1);

try
{
IAsyncResult result
= Sqldb.BeginExecuteReader(cmd, MyEndExecuteCallback, Sqldb);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

//当获取完毕执行该函数
privatevoid MyEndExecuteCallback(IAsyncResult result)
{
try
{
Database Sqldb
= (Database)result.AsyncState;
IDataReader reader
= db.EndExecuteReader(result);

College c
=new College((int)reader[0], (string)reader[1]);

MessageBox.Show(c.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Easily remove borders in Microsoft Edge in three simplified steps Easily remove borders in Microsoft Edge in three simplified steps Sep 02, 2023 pm 02:57 PM

Many users are dissatisfied with the white border around web pages in Microsoft Edge. They think it's unnecessary and distracting, and they're asking Microsoft to remove Microsoft Edge's bezels entirely. This is similar to the saying "don't fix what's not broken", but Microsoft doesn't seem to have taken this into account. Of course, it's a popular web browser that offers a variety of features, including a built-in ad blocker, tracking prevention, and a password manager. However, some users may find that the browser has a border around web pages. This border can be distracting or unsightly, and there are several ways to remove it. In a lengthy conversation on r/Edge, some regular non-internal users discovered,

Key differences between Microsoft 365 Copilot, Bing Chat Enterprise, and Copilot in Windows Key differences between Microsoft 365 Copilot, Bing Chat Enterprise, and Copilot in Windows Sep 23, 2023 pm 03:57 PM

Currently, Microsoft offers three different AI assistants to enterprise customers: Microsoft365Copilot, BingChatEnterprise, and Copilot in Windows. We would like to explain the differences between these three options. CopilotinWindows: Copilot in Windows is a powerful tool that helps you complete tasks faster and easier. You can seamlessly access Copilot from the taskbar or by pressing Win+C, and it will provide help next to any application you use. Copilot in Windows features new icons, new user experience and BingChat. it will be 2

Fix: Installation of this app package is not supported Fix: Installation of this app package is not supported Apr 13, 2023 am 11:43 AM

Microsoft distributes UWP (Universal Windows Platform) and desktop applications as .msixbundles. Apps and AppxBundle app packages in .Windows. Although the Msixbundle, Appx, and AppxPackage installers are reliable ways to sideload app packages, multiple users are unable to do so. Why am I getting an "App package is not supported" error? Some of our readers have received the "Should

How to log in to a Microsoft account on Windows 10 How to log in to a Microsoft account on Windows 10 Jan 01, 2024 pm 05:58 PM

You can log in with a Microsoft account in the win10 system, but there are still many friends who don’t know how to log in. Today I will bring you the method of logging in with a win10 Microsoft account. Come and take a look. How to log in to win10 microsoft account: 1. Click Start in the lower left corner and click the gear to open settings. 2. Then find "Account" and click to open. 3. After entering the account, click "Email and App Accounts" on the left. 4. Then click "Add Account" on the right. 5. After entering the account interface, many options will appear. Click the first "outlook". 6. Enter your account number in the Microsoft account window that appears. 7. After all is completed, you can

Fix 'Your account is currently unavailable' error in OneDrive Fix 'Your account is currently unavailable' error in OneDrive Sep 13, 2023 am 08:33 AM

Trying to log in in Windows doesn't work either. However, a check on the Microsoft account showed that there were no issues with it. I am able to log in and out of my Microsoft account on Windows and the web and am able to access all services. Only OneDrive appears to be affected. Microsoft's error message, like most of the time, isn't very helpful because it's too generic to be of much use. It starts with the following statement: "Your OneDrive or profile may be temporarily blocked because it is experiencing an unusually large amount of traffic. In this case, the block will be removed after 24 hours" This is followed by another sentence, Other possible reasons for temporary account suspension are listed: "

What version is enterprise? What version is enterprise? Jan 12, 2021 am 10:55 AM

enterprise is the enterprise version of the Windows system. The Windows enterprise version is mainly aimed at large and medium-sized enterprises. It has added a variety of practical functions such as Direct Access, Windows To Go Creator, AppLokcer, BranchCache, etc.

Windows 12 will be a free upgrade, no subscription required Windows 12 will be a free upgrade, no subscription required Oct 21, 2023 am 11:17 AM

Microsoft doesn't work with subscription-based versions of Windows 12, and you won't be charged any fees. People are still talking about Windows 12 being subscription-based, a rumor based on a string of code in a Windows 11 preview build. Some people are still wondering how Microsoft plans to make their next version of Windows a subscription model. It turns out that the rumor discussed by some media outlets was an "IoT Enterprise Subscription" based on Windows 11, not Windows vNext. For those who don’t know, Windows24H2 or WindowsvNext is the public name for Windows 12. Some media will win

What software is microsoft sql server? What software is microsoft sql server? Feb 28, 2023 pm 03:00 PM

Microsoft SQL Server is a relational database management system launched by Microsoft. It is a comprehensive database platform that uses integrated business intelligence (BI) tools to provide enterprise-level data management. It is easy to use, has good scalability, and has a high degree of integration with related software. High advantages. The SQL Server database engine provides more secure and reliable storage functions for relational data and structured data, allowing users to build and manage highly available and high-performance data applications for business.

See all articles