[c#] How to use Data Access Application Block?

How to use Data Access Application Block用于进行db操作。

ref links:
最好的guide

http://msdn.microsoft.com/en-us/library/ff953181(v=pandp.50).aspx

其中关于database connection manager的部分要留意:

Managing Connections

For many years, developers have fretted about the ideal way to manage connections in data access code. Connections are scarce, expensive in terms of resource usage, and can cause a big performance hit if not managed correctly. You must obviously open a connection before you can access data, and you should make sure it is closed after you have finished with it. However, if the operating system does actually create a new connection, and then closes and destroys it every time, execution in your applications would flow like molasses.

Instead, ADO.NET holds a pool of open connections that it hands out to applications that require them. Data access code must still go through the motions of calling the methods to create, open, and close connections, but ADO.NET automatically retrieves connections from the connection pool when possible, and decides when and whether to actually close the underlying connection and dispose it. The main issues arise when you have to decide when and how your code should call the Close method. The Data Access block helps to resolve these issues by automatically managing connections as far as is reasonably possible.

When you use the Data Access block to retrieve a DataSet, the ExecuteDataSet method automatically opens and closes the connection to the database. If an error occurs, it will ensure that the connection is closed. If you want to keep a connection open, perhaps to perform multiple operations over that connection, you can access the ActiveConnection property of your DbCommand object and open it before calling the ExecuteDataSet method. TheExecuteDataSet method will leave the connection open when it completes, so you must ensure that your code closes it afterwards.

In contrast, when you retrieve a DataReader or an XmlReader, the ExecuteReader method (or, in the case of the XmlReader, the ExecuteXmlReadermethod) must leave the connection open so that you can read the data. The ExecuteReader method sets the CommandBehavior property of the reader toCloseConnection so that the connection is closed when you dispose the reader. Commonly, you will use a using construct to ensure that the reader is disposed, as shown here:

using (IDataReader reader = db.ExecuteReader(cmd))
{
  // use the reader here
}

其他:

http://huan-lin.blogspot.hk/2012/09/data-access-application-block.html
http://msdn.microsoft.com/en-us/library/ff664719(v=pandp.50).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2



1. download "Microsoft Enterprise Library 5.0" msi file (not source code msi) from http://www.microsoft.com/en-us/download/details.aspx?id=15104


2. run the msi file to install "Microsoft Enterprise Library 5.0"


3. in your web app project, add following references:
* Microsoft.Practices.EnterpriseLibrary.Common (enterprise library shared library)
* Microsoft.Practices.EnterpriseLibrary.Data (enterprise library Data Access Application Block)
* Microsoft.Practices.ServiceLocation (Microsoft.Practices.ServiceLocation)

* System.Transactions




4. refer to http://msdn.microsoft.com/en-us/library/ff664387(v=pandp.50).aspx
right click web.config file, select "Edit Enterprise Library V5 Configuration" to add database connection setting.
 sql server connection settting example:
name: "VISITOR_LOG_DB"
  connectionString: "Data Source=.\SQLEXPRESS;Initial Catalog=VISITOR_LOG_DB;User Id=sa;PassWord=xxxx;"
  providerName: "System.Data.SqlClient"


(optional) set default db

and finally close the configuration tool, and select "Yes" to save it to web.config file

in fact, it will generate following codes in web.config
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration defaultDatabase="VISITOR_LOG_DB" />
  <connectionStrings>
    <add name="VISITOR_LOG_DB" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=VISITOR_LOG_DB;User Id=sa;PassWord=!234Qwer;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>


5. Example Codes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.Common;
using System.Transactions;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
namespace DAAB_Demo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected string data;
        protected void Page_Load(object sender, EventArgs e)
        {
            //create database connection
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("VISITOR_LOG_DB");

            //query example
            //string value="2' or '1'='1"; //test sql injection
            string value = "1";
            string strSql = "select * from VISITOR_LOG where VISITOR_NAME=@VISITOR_NAME";
            DbCommand cmd = db.GetSqlStringCommand(strSql);
            db.AddInParameter(cmd, "VISITOR_NAME", DbType.String, value);
            using (IDataReader rdr = db.ExecuteReader(cmd))
            {
                while (rdr.Read())
                {
                    data = rdr["VISITOR_COMPANY"].ToString() + "," + rdr["SIGNIN_TIME"].ToString();
                }
            }

            //Example: get first record and first column value
            cmd = db.GetSqlStringCommand("select count(*) from VISITOR_LOG where ID=@ID");
            db.AddInParameter(cmd, "ID", DbType.Int32, 1);
            int count=(int)db.ExecuteScalar(cmd);
            data = data + ", count=" + count;

            //update|insert|delete example
            cmd = db.GetSqlStringCommand("update VISITOR_LOG set SIGNIN_TIME=@SIGNIN_TIME where ID=@ID");
            db.AddInParameter(cmd, "SIGNIN_TIME", DbType.DateTime, DateTime.Now);
            db.AddInParameter(cmd, "ID", DbType.Int32, 1);
            db.ExecuteNonQuery(cmd);
            
            //transaction example
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    DbCommand cmd1 = db.GetSqlStringCommand("update VISITOR_LOG set VISITOR_COMPANY='AAA' where ID=1");
                    DbCommand cmd2 = db.GetSqlStringCommand("update VISITOR_LOG set VISITOR_COMPANY='ccc' where ID=1");

                    int affectedRows = db.ExecuteNonQuery(cmd1);
                    affectedRows += db.ExecuteNonQuery(cmd2);

                    if (affectedRows > 0)
                    {
                        throw new TransactionAbortedException("give up transaction");
                    }

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                data = "transaction fail: {" + ex.Message + "}";
            }
            catch (ApplicationException ex)
            {
                data = "app error: {" + ex.Message + "}";
            }
        }
    }
}





智能网联汽车的安全员高级考试涉及多个方面的专业知识,包括但不限于自动驾驶技术原理、车辆传感器融合、网络安全防护以及法律法规等内容。以下是针对该主题的一些核心知识点解析: ### 关于智能网联车安全员高级考试的核心内容 #### 1. 自动驾驶分级标准 国际自动机工程师学会(SAE International)定义了六个级别的自动驾驶等级,从L0到L5[^1]。其中,L3及以上级别需要安全员具备更高的应急处理能力。 #### 2. 车辆感知系统的组成与功能 智能网联车通常配备多种传感器,如激光雷达、毫米波雷达、摄像头超声波传感器等。这些设备协同工作以实现环境感知、障碍物检测等功能[^2]。 #### 3. 数据通信与网络安全 智能网联车依赖V2X(Vehicle-to-Everything)技术进行数据交换,在此过程中需防范潜在的网络攻击风险,例如中间人攻击或恶意软件入侵[^3]。 #### 4. 法律法规要求 不同国家地区对于无人驾驶测试及运营有着严格的规定,考生应熟悉当地交通法典中有关自动化驾驶部分的具体条款[^4]。 ```python # 示例代码:模拟简单决策逻辑 def decide_action(sensor_data): if sensor_data['obstacle'] and not sensor_data['emergency']: return 'slow_down' elif sensor_data['pedestrian_crossing']: return 'stop_and_yield' else: return 'continue_driving' example_input = {'obstacle': True, 'emergency': False, 'pedestrian_crossing': False} action = decide_action(example_input) print(f"Action to take: {action}") ``` 需要注意的是,“橙点同学”作为特定平台上的学习资源名称,并不提供官方认证的标准答案集;建议通过正规渠道获取教材并参加培训课程来准备此类资格认证考试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值