Newer
Older
IRIS_COLLECT / IOM_cs / irisDb / _MySqlHelper.cs
yangqianqian on 29 Dec 2020 2 KB first
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace IOM_cs.irisDb
{
    public class _MySqlHelper
    {
        public static MySqlConnection mySqlConnection = null;

        /// <summary>
        /// 打开数据库连接     
        /// </summary>
        /// <param name="sConnection"> connection </param>
        /// <returns> 0 on success </returns>
        public static int OpenDB()
        {
            int iRetval = -1;
            try
            {
                string server = ConfigHelper.GetAppConfig("server");
                string databaseName = ConfigHelper.GetAppConfig("databaseName");

                string databasePort = ConfigHelper.GetAppConfig("databasePort");
                string databaseUser = ConfigHelper.GetAppConfig("databaseUser");
                string databasePassword = ConfigHelper.GetAppConfig("databasePassword");
                string sConnection = "server=" + server
                                    + ";port=" + databasePort
                                    + ";user=" + databaseUser
                                    + ";database=" + databaseName
                                    + ";password=" + databasePassword
                                    + ";Charset=utf8"
                                    + ";Allow User Variables=True";

                mySqlConnection = new MySqlConnection(sConnection);
                mySqlConnection.Open();
                iRetval = 0;
            }
            catch (SqlException exSql)
            {
                iRetval = exSql.ErrorCode;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("EXCEPTION: " + ex.Message);
            }

            return iRetval;
        }

        /// <summary>
        /// 关闭数据库连接    
        /// </summary>
        /// <returns> 0 on success </returns>
        public static int CloseDB()
        {
            int iRetval = -1;
            try
            {
                mySqlConnection.Close();
            }
            catch (SqlException exSql)
            {
                iRetval = exSql.ErrorCode;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("EXCEPTION: " + ex.Message);
            }

            return iRetval;
        }

    }
}