• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >ASP.NET > 微软官方SqlHelper类 数据库辅助操作类 原创

微软官方SqlHelper类 数据库辅助操作类 原创

作者:yourber 字体:[增加 减小] 来源:互联网 时间:2017-05-11

yourber通过本文主要向大家介绍了微软sqlhelper,sqlhelper,sqlhelper类,sqlhelper.cs下载,sqlhelper类怎么用等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

数据库操作类真的没有必要自己去写,因为成熟的类库真的非常完善了,拿来直接用就好,省时省力。

本文就为大家介绍微软官方的程序PetShop4.0中的SqlHelper类,先来做一下简单的介绍,PetShop是一个范例,微软用它来展示.Net企业系统开发的能力。

那SqlHelper中封装了哪些方法呢?

里面的函数一堆,常用的就那几个,无非就是增删改查嘛,来看下几种常用的函数:

1.ExecuteNonQuery 执行增删改
2.ExecuteReader 执行查询
3.ExecuteScalar 返回首行首列

使用方法介绍

Web.config配置

<connectionStrings>
	<add name="ConnectionString" connectionString="server=127.0.0.1;uid=sa;pwd=ok;database=PetShop;Max Pool Size =512; Min Pool Size=0; Connection Lifetime = 300;packet size=1000;" providerName="System.Data.SqlClient" />
</connectionStrings>
</div>

调用函数的写法

sql = "UPDATE Student set Name = @Name WHERE Id = @Id";
SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[]{
 new SqlParameter("@Name", name),
 new SqlParameter("@Id", id)
});
</div>

这样调用就比较简化,而且比较灵活

源码呈上

/// <summary>
  /// The SqlHelper class is intended to encapsulate high performance, 
  /// scalable best practices for common uses of SqlClient.
  /// </summary>
  public abstract class SqlHelper
  {

    //数据库连接字符串
    public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString;

    #region 私有函数和方法

    /// <summary>
    /// This method is used to attach array of SqlParameters to a SqlCommand.
    /// 
    /// This method will assign a value of DbNull to any parameter with a direction of
    /// InputOutput and a value of null. 
    /// 
    /// This behavior will prevent default values from being used, but
    /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
    /// where the user provided no input value.
    /// </summary>
    /// <param name="command">The command to which the parameters will be added</param>
    /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
    private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
    {
      if (command == null) throw new ArgumentNullException("command");
      if (commandParameters != null)
      {
        foreach (SqlParameter p in commandParameters)
        {
          if (p != null)
          {
            // Check for derived output value with no value assigned
            if ((p.Direction == ParameterDirection.InputOutput ||
              p.Direction == ParameterDirection.Input) &&
              (p.Value == null))
            {
              p.Value = DBNull.Value;
            }
            command.Parameters.Add(p);
          }
        }
      }
    }

    /// <summary>
    /// This method assigns dataRow column values to an array of SqlParameters
    /// </summary>
    /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
    /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
    private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
    {
      if ((commandParameters == null) || (dataRow == null))
      {
        // Do nothing if we get no data
        return;
      }

      int i = 0;
      // Set the parameters values
      foreach (SqlParameter commandParameter in commandParameters)
      {
        // Check the parameter name
        if (commandParameter.ParameterName == null ||
          commandParameter.ParameterName.Length <= 1)
          throw new Exception(
            string.Format(
              "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
              i, commandParameter.ParameterName));
        if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
          commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
        i++;
      }
    }

    /// <summary>
    /// This method assigns an array of values to an array of SqlParameters
    /// </summary>
    /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
    /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
    private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
    {
      if ((commandParameters == null) || (parameterValues == null))
      {
        // Do nothing if we get no data
        return;
      }

      // We must have the same number of values as we pave parameters to put them in
      if (commandParameters.Length != parameterValues.Length)
      {
        throw new ArgumentException("Parameter count does not match Parameter Value count.");
      }

      // Iterate through the SqlParameters, assigning the values from the corresponding position in the 
      // value array
      for (int i = 0, j = commandParameters.Length; i < j; i++)
      {
        // If the current array value derives from IDbDataParameter, then assign its Value property
        if (parameterValues[i] is IDbDataParameter)
        {
          IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
          if (paramInstance.Value == null)
          {
            commandParameters[i].Value = DBNull.Value;
          }
          else
          {
            commandParameters[i].Value = paramInstance.Value;
          }
        }
        else if (parameterValues[i] == null)
        {
          commandParameters[i].Value = DBNull.Value;
        }
        else
        {
          commandParameters[i].Value = parameterValues[i];
        }
      }
    }

    /// <summary>
    /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters 
    /// to the provided command
    /// </summary>
    /// <param name="command">The SqlCommand to be prepared</param>
    /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
    /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
    /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
    private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
    {
      if (command == null) throw new ArgumentNullException("command");
      if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");

      // If the provided connection is not open, we will open it
      if (connection.State != ConnectionState.Open)
      {
        mustCloseConnection = true;
        connection.Open();
      }
      else
      {
        mustCloseConnection = false;
      }

      // Associa



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 微软官方SqlHelper类 数据库辅助操作类 原创

相关文章

  • 2017-05-11asp.net 组件开发中的内嵌资源引用
  • 2017-05-11在ASP.NET 2.0中操作数据之十四:使用FormView 的模板
  • 2017-05-11Asp.Mvc 2.0用户服务器验证实例讲解(4)
  • 2017-05-11ASP.NET中ServerPush用法实例分析
  • 2017-05-11asp.net项目开发中用到的小技巧
  • 2017-05-11灵活掌握asp.net中gridview控件的多种使用方法(上)
  • 2017-05-11vs2010制作简单的asp.net网站
  • 2017-05-11c# table 控件用法
  • 2017-05-11asp.net分页控件使用详解【附实例下载】
  • 2017-05-11asp.net 过滤图片标签的正则

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • ASP.NET中使用IFRAME建立类Modal窗口
    • ajax添加数据后如何在网页显示
    • asp.net使用jQuery获取RadioButtonList成员选中内容和值示例
    • ASP.NET技巧:做个DataList可分页的数据源
    • ASP.NET repeater添加序号列的方法
    • asp.net中调用存储过程的方法
    • asp.net创建位图生成验证图片类(验证码类)
    • .NET中OpenFileDialog使用线程报错的解决方法
    • WebAPI 实现前后端分离的示例
    • CefSharp v62修改方法(支持.net4.0)

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有