| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394 | using System;using System.Collections.Generic;using System.Linq;using System.Text;using Npgsql;using Aitex.Core.RT.Log;using System.Data;using Aitex.Core.Utilities;using DocumentFormat.OpenXml.Office.Word;namespace Aitex.Core.RT.DBCore{    public enum DataBaseStatus    {        Close,        Open,        Error    }    public class PostgresqlDB    {        NpgsqlConnection _conn;        string _connectionString;        string _dbName;        Retry _retryConnection = new Retry();        private int _closeMaxTime = 10;        private int _closeTime    = 0;        public DataBaseStatus DBStatus        {            get             {                //超过允许异常关闭的次数                if (_closeTime >= _closeMaxTime)                    return DataBaseStatus.Error;                else                    return (_conn != null && _conn.State == ConnectionState.Open) ? DataBaseStatus.Open : DataBaseStatus.Close;            }        }        public PostgresqlDB()        {        }        public bool Open(string connectionString, string dbName)        {            _connectionString = connectionString;            _dbName = dbName;            bool result = true;            try            {                if (_conn != null)                    _conn.Close();                _conn = new NpgsqlConnection(connectionString);                _conn.Open();                if (!string.IsNullOrEmpty(dbName))                    CreateDBIfNotExisted(dbName);            }            catch (Exception ex)            {                if (_conn != null)                {                    _conn.Close();                    _conn = null;                }                result = false;                LOG.WriteExeption(ex);            }            _retryConnection.Result = result;            //if (_retryConnection.IsErrored)            return result;        }        bool Open()        {            return Open(_connectionString, _dbName);        }        void PrepareCommand(NpgsqlCommand cmd, NpgsqlConnection conn, string cmdText, params object[] p)        {            cmd.Parameters.Clear();            cmd.Connection = conn;            cmd.CommandText = cmdText;            cmd.CommandType = CommandType.Text;            if (p != null)            {                foreach (object parm in p)                    cmd.Parameters.AddWithValue(string.Empty, parm);            }        }        public int ExecuteNonQuery(string cmdText, params object[] p)        {            try            {                using (NpgsqlCommand command = new NpgsqlCommand())                {                    PrepareCommand(command, _conn, cmdText, p);                    return command.ExecuteNonQuery();                }            }            catch            {                _closeTime++;                Close();                throw;            }        }        public DataSet ExecuteDataset(string cmdText, params object[] p)        {            try            {                DataSet ds = new DataSet();                using (var connection = new NpgsqlConnection(_connectionString))                {                    connection.Open();                    connection.ChangeDatabase(_dbName);                    using (NpgsqlCommand command = new NpgsqlCommand())                    {                        try                        {                            PrepareCommand(command, connection, cmdText, p);                            NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);                            da.Fill(ds);                        }                        catch (Exception ex)                        {                            LOG.WriteExeption("执行查询出错," + cmdText, ex);                        }                    }                }                return ds;            }            catch (Exception ex)            {                LOG.WriteExeption("执行查询出错," + cmdText, ex);            }            return null;        }        public NpgsqlDataReader ExecuteReader(string cmdText, params object[] p)        {            try            {                using (NpgsqlCommand command = new NpgsqlCommand())                {                    PrepareCommand(command, _conn, cmdText, p);                    return command.ExecuteReader(CommandBehavior.CloseConnection);                }            }            catch            {                Close();                throw;            }        }        public int GetAllCount(string cmdText, params object[] p)        {            using (var connection = new NpgsqlConnection(_connectionString))            {                connection.Open();                connection.ChangeDatabase(_dbName);                using (NpgsqlCommand command = new NpgsqlCommand())                {                    try                    {                        PrepareCommand(command, connection, cmdText, p);                                               return Convert.ToInt32( command.ExecuteScalar());                    }                    catch (Exception ex)                    {                        LOG.WriteExeption("执行查询出错," + cmdText, ex);                        return 0;                    }                }            }            //using (var connection = new NpgsqlConnection(_connectionString))            //{            //    using (NpgsqlCommand command = new NpgsqlCommand(cmdText,connection))            //    {            //        try            //        {            //            connection.Open();            //            object obj = command.ExecuteScalar();            //            return (Int32)command.ExecuteScalar();            //        }            //        catch (Exception ex)            //        {            //            LOG.WriteExeption("执行查询出错," + cmdText, ex);            //            return 0;            //        }            //    }            //}        }        public bool ActiveConnection()        {            if (_conn != null && _conn.State == ConnectionState.Open)                return true;            return Open();        }        public void Close()        {            try            {                if (_conn != null)                    _conn.Close();                _conn = null;            }            catch (Exception ex)            {                LOG.WriteExeption(ex);            }        }        public void CreateDBIfNotExisted(string db)        {            NpgsqlDataReader reader =                ExecuteReader(string.Format(@"select datname from pg_catalog.pg_database where datname='{0}'", db));            if (!reader.HasRows)            {                string sql = string.Format(@"                                    CREATE DATABASE {0}                                    WITH OWNER = postgres                                   ENCODING = 'UTF8'                                   TABLESPACE = pg_default                                   CONNECTION LIMIT = -1", db);                ExecuteNonQuery(sql);            }            try            {                _conn.ChangeDatabase(db);            }            catch            {                _conn.Close();                throw;            }        }        public void CreateTableIndexIfNotExisted(string table, string index, string sql)        {            NpgsqlDataReader reader = ExecuteReader($"select* from pg_indexes where tablename='{table}' and indexname = '{index}'");            if (!reader.HasRows)            {                ExecuteNonQuery(sql);            }        }        public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID,            string primaryKey)        {            NpgsqlDataReader reader =                ExecuteReader(                    string.Format(@"select column_name from information_schema.columns where table_name = '{0}'",                        table));            if (!reader.HasRows)            {                string cols = addPID ? " \"PID\" serial NOT NULL," : "";                foreach (var item in columns)                {                    if (item.Value == typeof(int))                        cols += string.Format("\"{0}\" integer,", item.Key);                    else if (item.Value == typeof(string))                        cols += string.Format("\"{0}\" text,", item.Key);                    else if (item.Value == typeof(DateTime))                        cols += string.Format("\"{0}\" timestamp without time zone,", item.Key);                    else if (item.Value == typeof(bool))                        cols += string.Format("\"{0}\" boolean,", item.Key);                    else if (item.Value == typeof(float))                        cols += string.Format("\"{0}\" real,", item.Key);                }                if (string.IsNullOrEmpty(primaryKey))                {                    if (cols.LastIndexOf(',') == cols.Length - 1)                        cols = cols.Remove(cols.Length - 1);                }                else                {                    cols += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (\"{1}\" )", table, primaryKey);                }                ExecuteNonQuery(string.Format("CREATE TABLE \"{0}\"({1})WITH ( OIDS=FALSE );", table, cols));            }            else            {                CreateTableColumn(table, columns);            }        }        public void CreateTableColumn(string tableName, Dictionary<string, Type> columns)        {            try            {                //query if table already exist?                string sqlTblDefine =                    string.Format("select column_name from information_schema.columns where table_name = '{0}';",                        tableName);                NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);                var tblDefineData = cmdTblDefine.ExecuteReader();                string tblAlertString = string.Empty;                List<string> colNameList = new List<string>();                while (tblDefineData.Read())                {                    for (int i = 0; i < tblDefineData.FieldCount; i++)                        colNameList.Add(tblDefineData[i].ToString());                }                tblDefineData.Close();                if (colNameList.Count > 0)                {                    //table exist                    foreach (var column in columns)                    {                        if (!colNameList.Contains(column.Key))                        {                            if (column.Value == typeof(Boolean))                            {                                tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",                                    tableName, column.Key, "Boolean");                            }                            else if (column.Value == typeof(double) || column.Value == typeof(float))                            {                                tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",                                    tableName, column.Key, "real");                            }                            else if (column.Value == typeof(DateTime))                            {                                tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",                                    tableName, column.Key, "timestamp without time zone");                            }                            else if (column.Value == typeof(int) || column.Value == typeof(ushort) ||                                     column.Value == typeof(short))                            {                                tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",                                    tableName, column.Key, "integer");                            }                            else                            {                                tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",                                    tableName, column.Key, "text");                            }                        }                    }                    if (!string.IsNullOrEmpty(tblAlertString))                    {                        try                        {                            NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);                            alertTblCmd.ExecuteNonQuery();                        }                        catch (Exception ex)                        {                            LOG.WriteExeption(ex);                        }                    }                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);            }        }    }}
 |