• SqlHelper.cs


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    namespace _001
    {
        public static class SqlHelper
        {
            //定义一个连接字符串,
            //readonly,只能在初始化和构造函数中赋值
            private static readonly string conStr=ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;

            //1.执行增insert 删delete 改update的方法;
            public static int ExecuteNonQuery(string sql,params SqlParameter[] pms)
            {
                using (SqlConnection conn = new SqlConnection(conStr))
                {
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        if (pms != null)
                        {
                            cmd.Parameters.AddRange(pms);
                        }
                        conn.Open();
                        return cmd.ExecuteNonQuery();
                    }
                }
            }

            //2.执行查询,返回单个值的方法
            //ExecuteScalar()
            public static object ExecuteScalar(string sql, params SqlParameter[] pms)
            {
                using (SqlConnection conn = new SqlConnection(conStr))
                {
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        if (pms != null)
                        {
                            cmd.Parameters.AddRange(pms);
                        }
                        conn.Open();
                        return cmd.ExecuteScalar();
                    }
                }
            }

            //3.执行查询,返回多行,多列的方法
            //ExecuteReader
            public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
            {
                SqlConnection conn = new SqlConnection(conStr);
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        if (pms != null)
                        {
                            cmd.Parameters.AddRange(pms);
                        }
                        try
                        {
                            conn.Open();
                            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                        }
                        catch
                        {
                            conn.Close();
                            conn.Dispose();
                            throw;
                        }
                    }
            }
        }
    }

  • 相关阅读:
    转 闭包简单理解
    mac 利用 sshpass 自动登录
    阮一峰 IaaS,PaaS,SaaS 的区别
    YMP运行初始化步骤
    强烈推荐 在线接口文档管理工具 小幺鸡 小团队可以省掉测试了
    springboot JSP 404
    并发测试 JavaDemo
    JS刷新当前页面的几种方法总结
    jquery checkbox勾选/取消勾选只能操作一次的诡异问题
    微信网页 第三方登录原理详解(转)
  • 原文地址:https://www.cnblogs.com/HarryChis/p/10368742.html
Copyright © 2020-2023  润新知