C# DbHepler

hellwrol發表於2020-12-10

1.xml 資料庫配置檔案

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
 <add name="test" connectionString="Data Source=.;Initial Catalog=Test;User Id=sa;PassWord=123"/>
</connectionStrings>
</configuration>

2.運算元據庫

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

 namespace WindowsFormsApplication1
 {
 public static  class DbHelper
{
 public static readonly string constr =       ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
    //1.執行增刪改的方法
    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();
            }
        }
    }
    //2.執行查詢,返回單個值的方法
    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();
            }
        }

    }
    //3.執行查詢,返回多行,多列的方法
    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
            {
                con.Close();
                con.Dispose();
                throw;
            }
        }
    }
}

}