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

namespace MesWork
{
    public class SqlOperation
    {
        public static bool ExecuteStoredProcedure(string name, SqlParameter[] sqlParameters, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(name, MesWorkForm.ConnectionString, ref sqlParameters, out errorMessage);
        }
        public static bool ExecuteStoredProcedure(string name, SqlParameter[] sqlParameters, out DataTable dt, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(name, MesWorkForm.ConnectionString, ref sqlParameters, out dt, out errorMessage);
        }
        public static bool ExecuteStoredProcedure(string name, SqlParameter[] sqlParameters, out DataSet ds, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(name, MesWorkForm.ConnectionString, ref sqlParameters, out ds, out errorMessage);
        }
        public static bool ExecuteSql(string sql, out DataTable dt, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteSql(sql, MesWorkForm.ConnectionString, out dt, out errorMessage);
        }

        public static bool ExecuteSql(string sql, out DataSet ds, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteDataset(sql, MesWorkForm.ConnectionString, out ds, out errorMessage);
        }

        public static bool ExecuteSql(string sql, out string errorMessage)
        {
            return DataLinkMesWork.SQLCommon.ExecuteSql(sql, MesWorkForm.ConnectionString, out errorMessage);
        }


        /// <summary>
        /// 通过SqlBulkCopy复制table数据到数据库
        /// </summary>
        /// <param name="dataset"></param>
        public static bool SqlbulkcopyInsert(DataTable dt, out string ErrMsg)
        {
            bool success = false;
            ErrMsg = "";
            try
            {
                // SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectString, SqlBulkCopyOptions.KeepIdentity);//删除自增ID插入原始数据
                SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(MesWorkForm.ConnectionString, SqlBulkCopyOptions.UseInternalTransaction);//批量事务处理
                sqlbulkcopy.DestinationTableName = dt.TableName;//数据库中的表名
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    var columnName = dt.Columns[i].ColumnName.ToString();
                    sqlbulkcopy.ColumnMappings.Add(columnName, columnName);
                }
                sqlbulkcopy.WriteToServer(dt);
                success = true;
            }
            catch (Exception err)
            {
                ErrMsg = err.Message;
            }
            return success;

        }


    }
}
