using System;
using System.Data;
using System.Data.SqlClient;

namespace DatabaseClient
{
    class MssqlClient : DBClient
    {
        SqlConnection conn = null;
        
        public MssqlClient(){}

        public override void Connect(string connString)
        {
            try
            {
                conn = new SqlConnection(connString);
            }
            catch (Exception err)
            {
                GlobalVar.log.Error(err.Message);
            }
        }

        public override DataTable ExecQuery(string sql)
        {
            DataTable dt = null;
            try
            {
                if (conn != null)
                {
                    conn.Open();

                    var cmd = new SqlCommand(sql, conn);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    conn.Close();
                    if (ds.Tables.Count > 0)
                    {
                        dt = ds.Tables[0];
                    }
                }

            }
            catch (Exception err)
            {
                GlobalVar.log.Error(err.Message);
            }

            return dt;
        }

        public override int ExecNonQuery(string sql)
        {
            int res = 0;
            try
            {
                if (conn!=null)
                {
                    var cmd = new SqlCommand(sql, conn);
                    conn.Open();
                    res = cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            catch (Exception err)
            {
                GlobalVar.log.Error(err.Message);
            }
            return res;
        }
    }
}