using System;
using MySql.Data.MySqlClient;
using System.Reflection;
using System.Data.Odbc;
using irisHelper;
using irisMemory;

namespace irisDataBase
{
    public class DatabaseServer
    {        
        public static string serverIp = null;
        public static MySqlConnection mySqlConnectionServer;
        /// <summary>
        /// 打开数据库连接
        /// </summary>
        /// <param name="sConnection"> connection </param>
        /// <returns> 0 on success </returns>
        public static int OpenDB(DbServerConfig dbServerConfig)
        {
            int iRetval = -1;
            try
            {
                string sConnection = "server=" + dbServerConfig.ServerIp
                                   + ";port=" + dbServerConfig.ServerDatabasePort
                                   + ";user=" + dbServerConfig.ServerDatabaseUser
                                   + ";database=" + dbServerConfig.ServerDatabaseName
                                   + ";password=" + dbServerConfig.ServerDatabasePassword
                                   + ";Charset=utf8"
                                   + ";Allow User Variables=True";

                mySqlConnectionServer = new MySqlConnection(sConnection);
                mySqlConnectionServer.Open();  
                
                iRetval = 0;
            }
            catch (OdbcException exSql)
            {
                iRetval = exSql.ErrorCode;
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "  Server_OpenDB : " + exSql.Message);
            }
            catch (Exception ex)
            {
                iRetval = -1;
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "  Server_OpenDB : " + ex.Message);
            }

            return iRetval;
        }
        /// <summary>
        /// 关闭数据库连接    
        /// </summary>
        /// <returns> 0 on success </returns>
        public static int CloseDB()
        {
            int iRetval = -1;
            try
            {
                mySqlConnectionServer.Close();
            }
            catch (MySqlException exSql)
            {
                iRetval = exSql.ErrorCode;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "  Server_CloseDB : " + ex.Message);
            }

            return iRetval;
        }
        
    }
}