C#-DBHelper

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

namespace Common
{
     public class DBHelper
    {
        private string strConn;
        private SqlConnection conn;
        public DBHelper(string ConnectionName)
        {
            strConn = GetConfigString(ConnectionName);
            conn = new SqlConnection(strConn);
 
        }
        public static string GetConfigString(string ConnectionName)
        {
            string strConfig = ConfigurationManager.AppSettings[ConnectionName];
            return strConfig;

        }
        public DataTable GetDataTable(string strSql)
        {
            DataTable dt = new DataTable();
            try
            {
                System.Data.SqlClient.SqlDataAdapter dr = new SqlDataAdapter(strSql, conn);
                conn.Open();
                dr.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }

        }
        public void ExecuteNonQuery(string strSql)
        {
            try
            {
                SqlCommand comd = new SqlCommand(strSql, conn);
                conn.Open();
                comd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }

        }
        public bool SqlBulkCopy(DataTable dtData, string strDataTableName)
        {
            try
            {
                using (SqlBulkCopy Tsbc = new SqlBulkCopy(strConn))
                {
                    Tsbc.DestinationTableName = strDataTableName;

                    Tsbc.WriteToServer(dtData);
                }
                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
            }
        }



    }
}

 

posted @ 2019-05-09 10:13  JinweiChang  阅读(311)  评论(0编辑  收藏  举报