当前位置: 代码迷 >> 综合 >> SqlHelper.cs
  详细解决方案

SqlHelper.cs

热度:50   发布时间:2023-12-14 17:12:05.0

1在web.app配置文件添加连接字符串

<connectionStrings>

  <add  name="itcast" connectionString="server=.;uid=sa;pwd=123;database=itcast">

</connectionStrings>

//SqlHelper.cs

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

namespace aspWeb
{
    public class SqlHelper
    {
        private static readonly string constr =
              ConfigurationManager.ConnectionStrings["aspWeb_db"].ConnectionString;
        //执行增删改
        public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
        {
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    if (pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteNonQuery();

                }
            }
        }
        //返回单个值
        public static object ExecuteScalar(string sql,params SqlParameter[] pms)
        {
            using(SqlConnection con = new SqlConnection(constr))
            {
                using(SqlCommand cmd = new SqlCommand(sql,con))
                {
                    if(pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }
        //返回SqlDataReader
        public static SqlDataReader  ExecuteReader(string sql,params SqlParameter[] pms)
        {
            SqlConnection con = new SqlConnection(constr);
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                try
                {
                    con.Open();
                    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                }
                catch(Exception)
                {
                    con.Close();
                    con.Dispose();
                    throw;
                }
            }
        }

        //执行返回DataTable
        public static DataTable ExecuteDataTable(string sql,params SqlParameter[] pms)
        {
            DataTable dt = new DataTable();
            using(SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
            {
                if(pms != null)
                {
                    adapter.SelectCommand.Parameters.AddRange(pms);
                }
                adapter.Fill(dt);
                    return dt;
            }
        }
    }
}