Spring.Net学习笔记(二)-数据访问器

Spring对ADO.NET也提供了支持,依赖与程序集Spring.Data.dll

IDbProvider

IDbProvider定义了数据访问提供器的基础,配置如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler,Spring.Core"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler,Spring.Core"/>
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="config://spring/objects"></resource>
    </context>
    <objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database">
     <db:provider id="DbProvider" provider="System.Data.SqlClient" 
                  connectionString="server=.;database=KMS;uid=sa;pwd=123456"/>
      <object id="adoTemplate" type="Spring.Data.Core.AdoTemplate,Spring.Data">
        <property name="DbProvider" ref="DbProvider"></property>
      </object>
    </objects>
  </spring>
  
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

获取数据IDbProvider的方法

Spring.Context.IApplicationContext context = Spring.Context.Support.ContextRegistry.GetContext();
Spring.Data.Common.IDbProvider provider = context.GetObject("DbProvider") as IDbProvider;

AdoTemplate

AdoTemplate有两个,

一个泛型,定义为:Spring.Data.Generic.AdoTemplate

一个非泛型,定义为:Spring.Data.Core.AdoTemplate

使用如下

Spring.Context.IApplicationContext context = Spring.Context.Support.ContextRegistry.GetContext();
Spring.Data.Common.IDbProvider provider = context.GetObject("DbProvider") as IDbProvider;

Spring.Data.Core.AdoTemplate ado = new Spring.Data.Core.AdoTemplate(provider);
Spring.Data.Generic.AdoTemplate ado2 =new AdoTemplate(provider);
//Console.WriteLine(person);

配置文件中已经将adoTemplate注入,那么直接使用如下

Spring.Data.Core.AdoTemplate adoTemplate = context.GetObject("adoTemplate") as Spring.Data.Core.AdoTemplate;
string result = adoTemplate.ExecuteScalar(CommandType.Text, "select NickName from Blog_User").ToString();
Console.WriteLine(result);
posted @ 2016-02-22 20:23  Kimisme  阅读(1038)  评论(0编辑  收藏  举报