/*
         *
         * 旧版已弃用
         * public string GetTableJson(string TableName, Xu.Common.DbType type)
         * {
         *  if (type == Xu.Common.DbType.MySql)
         *  {
         *      MySqlConnection conn = new MySqlConnection(Xu.Common.Common.SetConfig("SqlString"));
         *      string sql = "select * from information_schema.COLUMNS where table_name = '" + TableName + "'";
         *      MySqlDataAdapter ds = new MySqlDataAdapter(sql, conn);
         *      conn.Open();
         *      DataTable dt = new DataTable();
         *      ds.Fill(dt);
         *      conn.Close();
         *      return JsonConvert.SerializeObject(dt);
         *  }
         *  else if (type == Xu.Common.DbType.SqlServer)
         *  {
         *      SqlConnection conn = new SqlConnection(Common.SetConfig("SqlString"));
         *      string sql = "select * from "+ Common.SetConfig("DataBaseName") +".information_schema.COLUMNS where table_name = '" + TableName +"'";
         *      SqlDataAdapter apter = new SqlDataAdapter(sql, conn);
         *      conn.Open();
         *      DataSet ds = new DataSet();
         *      DataTable dt = new DataTable();
         *      apter.Fill(ds);
         *      dt = ds.Tables[0];
         *      conn.Close();
         *      return JsonConvert.SerializeObject(dt);
         *  }
         *  else return null;
         * }
         */

        /// <summary>
        /// 获取表JSON
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="type">数据库类型</param>
        /// <returns></returns>
        public string GetTableJson(string TableName, SqlSugar.DbType type)
        {
            SqlSugarClient db = new SqlSugarClient(
                new ConnectionConfig()
            {
                ConnectionString      = Common.SetConfig("SqlString"),
                DbType                = type,                 //设置数据库类型
                IsAutoCloseConnection = true,                 //自动释放数据务,如果存在事务,在事务结束后释放
                InitKeyType           = InitKeyType.Attribute //从实体特性中读取主键自增列信息
            });

            try
            {
                DataTable list = new DataTable();
                if (type == SqlSugar.DbType.MySql)
                {
                    list = db.Queryable <Models>().Where(e => e.TABLE_NAME == TableName).ToDataTable();
                }//
                else if (type == SqlSugar.DbType.SqlServer)
                {
                    list = db.Queryable <INFORMATION_SCHEMA>().Where(e => e.TABLE_NAME == TableName).ToDataTable();
                    list.Columns["CHARACTER_MAXIMUM_LENGTH"].ColumnName = "COLUMN_TYPE";
                }
                else if (type == SqlSugar.DbType.Oracle)
                {
                    list = db.Queryable <USER_TAB_COLUMNS>().Where(e => e.TABLE_NAME == TableName.ToUpper()).ToDataTable();
                    list.Columns["NULLABLE"].ColumnName = "IS_NULLABLE";
                }
                return(JsonConvert.SerializeObject(list));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        public DbContext()
        {
            var dbType = new SqlSugar.DbType();

            if (dbtype == null)
            {
                dbtype = (string)GetAppSetting("DBType", typeof(string));
            }
            switch (dbtype)
            {
            case "mysql": dbType = DbType.MySql; break;

            case "sqlserver": dbType = DbType.SqlServer; break;

            case "postgresql": dbType = DbType.PostgreSQL; break;

            case "sqlite": dbType = DbType.Sqlite; break;

            case "oracle": dbType = DbType.Oracle; break;
            }
            if (connectstring == null)
            {
                connectstring = (string)GetAppSetting("DBConnectionString", typeof(string));
            }

            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString      = connectstring,
                DbType                = dbType,
                IsAutoCloseConnection = true,
                InitKeyType           = InitKeyType.Attribute
            });
        }
Beispiel #3
0
        /// <summary>
        /// 自定义连接
        /// </summary>
        /// <param name="ConnectionString">数据库连接字符串</param>
        /// <param name="DBType">mysql,sqlserver,postgresql,oracle,sqlite</param>
        public DbContext(string ConnectionString, string DBType)
        {
            connectstring = ConnectionString;
            var dbType = new SqlSugar.DbType();

            // 判断数据库类型
            switch (DBType.ToLower())
            {
            case "mysql": dbType = DbType.MySql; break;

            case "sqlserver": dbType = DbType.SqlServer; break;

            case "postgresql": dbType = DbType.PostgreSQL; break;

            case "sqlite": dbType = DbType.Sqlite; break;

            case "oracle": dbType = DbType.Oracle; break;
            }
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString      = connectstring,
                DbType                = dbType,
                IsAutoCloseConnection = true,
                InitKeyType           = InitKeyType.Attribute
            });
        }
Beispiel #4
0
        /// <summary>
        /// 自定义连接
        /// </summary>
        /// <param name="ConnectionString">数据库连接字符串</param>
        /// <param name="DBType">mysql,sqlserver,postgresql,oracle,sqlite</param>
        public static void Init(string connectionString, string DBType)
        {
            try
            {
                var dbType = new SqlSugar.DbType();
                // 判断数据库类型
                switch (DBType.ToLower())
                {
                case "mysql":
                    dbType            = DbType.MySql;
                    connectionString += "Allow User Variables=True;AllowZeroDateTime=True;ConvertZeroDateTime=True;SslMode=none;";
                    break;

                case "sqlserver": dbType = DbType.SqlServer; break;

                case "postgresql": dbType = DbType.PostgreSQL; break;

                case "sqlite": dbType = DbType.Sqlite; break;

                case "oracle": dbType = DbType.Oracle; break;
                }
                Client = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString      = connectionString,
                    DbType                = dbType,
                    IsAutoCloseConnection = true,
                    InitKeyType           = InitKeyType.Attribute
                });
            }
            catch (System.Exception)
            {
                throw;
            }
        }
        public SqlSugarContext(string connstr, DbType dbType = DbType.SqlServer)
        {
            SqlSugar.DbType _dbType = SqlSugar.DbType.SqlServer;
            switch (dbType)
            {
            case DbType.MySql:
                _dbType = SqlSugar.DbType.MySql;
                break;

            case DbType.SqlServer:
            default:
                _dbType = SqlSugar.DbType.SqlServer;
                break;
            }
            _db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connstr, DbType = _dbType, IsAutoCloseConnection = true
            });
#if DEBUG
            _db.Ado.IsEnableLogEvent = true;
            _db.Ado.LogEventStarting = (sql, pars) =>
            {
                System.Diagnostics.Debug.Write(sql);
            };
#endif
            _db = SqlClient.GetInstance();
        }
Beispiel #6
0
 /// <summary>
 /// 获取SqlSugarClient
 /// </summary>
 /// <param name="_conString">连接字符串</param>
 /// <param name="_dbType">数据库类型</param>
 /// <returns></returns>
 private SqlSugarClient GetClient(string _conString, SqlSugar.DbType _dbType)
 {
     return(new SqlSugarClient(new ConnectionConfig()
     {
         ConnectionString = _conString,
         DbType = _dbType,
         InitKeyType = InitKeyType.Attribute, //从特性读取主键和自增列信息
         IsAutoCloseConnection = true,        //开启自动释放模式
     }));
 }
Beispiel #7
0
 public OleExec(string strConn, SqlSugar.DbType dbtype)
 {
     _connStr = strConn;
     //_conn = new OleDbConnection(_connStr);
     //_conn.Open();
     //_comm = new OleDbCommand();
     //_adp = new OleDbDataAdapter(_comm);
     db = new SqlSugarClient(new ConnectionConfig()
     {
         ConnectionString      = _connStr,
         DbType                = dbtype,
         IsAutoCloseConnection = false,
         InitKeyType           = InitKeyType.Attribute
     });
     db.Open();
 }
Beispiel #8
0
        public static SqlSugarClient GetContext(string connectionString, SqlSugar.DbType type)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception("请配置连接字符串!");
            }
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString      = connectionString,
                DbType                = type,
                IsAutoCloseConnection = true,
                InitKeyType           = InitKeyType.Attribute
            });

            return(db);
        }
Beispiel #9
0
        /// <summary>
        /// 初始化ORM连接对象
        /// </summary>
        /// <param name="commandTimeOut">等待超时时间, 默认为30秒 (单位: 秒)</param>
        /// <param name="dbType">数据库类型</param>
        /// <param name="isAutoCloseConnection">是否自动关闭数据库连接, 默认不是, 如果设置为true, 则会在每次操作完数据库后, 即时关闭, 如果一个方法里面多次操作了数据库, 建议保持为false, 否则可能会引发性能问题</param>
        private static SqlSugarClient InitDB(int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql, bool isAutoCloseConnection = false)
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString          = ConnectionString,
                DbType                    = dbType,
                InitKeyType               = InitKeyType.Attribute,//使用特性识别主键
                IsAutoCloseConnection     = isAutoCloseConnection,
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    DataInfoCacheService = new RedisCache() //Reids缓存实现类
                }
            });

            db.Ado.CommandTimeOut = commandTimeOut;

            #region 记录SQL日志
            ExecuteSqlLogHandler _executeSqlLog = null;
            db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
            {
                string par = string.Empty;
                if (pars.Length > 0)
                {
                    Dictionary <string, object> dic = pars.ToDictionary(k => k.ParameterName, v => v.Value);
                    par = JsonConvert.SerializeObject(dic).Replace(":", "=");
                }
                _executeSqlLog = new ExecuteSqlLogHandler(sql, par);
            };
            db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
            {
                _executeSqlLog.WriteLog();
            };

            db.Aop.OnError = (exp) =>//执行SQL 错误事件
            {
                _executeSqlLog.LogInfo.IsFail  = 1;
                _executeSqlLog.LogInfo.Massage = exp.Message;
                _executeSqlLog.WriteLog();
            };
            #endregion

            return(db);
        }
Beispiel #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.textBox1.Text) || this.textBox1.Text == "请输入数据库连接字符串")
            {
                MessageBox.Show("请输入数据库连接字符串");
            }
            else if (this.comboBox1.SelectedItem == null)
            {
                MessageBox.Show("请选择数据库类型");
            }
            else
            {
                var connstr = this.textBox1.Text;
                //默认mssql
                SqlSugar.DbType dbtype = SqlSugar.DbType.SqlServer;

                if (this.comboBox1.SelectedItem == "MySQL")
                {
                    dbtype = SqlSugar.DbType.MySql;
                }
                else if (this.comboBox1.SelectedItem == "Oracle")
                {
                    dbtype = SqlSugar.DbType.Oracle;
                }

                ConnectionConfig config = new ConnectionConfig()
                {
                    ConnectionString      = this.textBox1.Text,
                    DbType                = dbtype,
                    IsAutoCloseConnection = true,
                    InitKeyType           = InitKeyType.SystemTable
                };

                using (var db = new SqlSugarClient(config))
                {
                    var tablelist = db.DbMaintenance.GetTableInfoList();
                    this.ckbDtTabls.DataSource    = tablelist;
                    this.ckbDtTabls.ValueMember   = "Name";
                    this.ckbDtTabls.DisplayMember = "Description";
                }
            }
        }
        public string GetTableJson(string TableName, SqlSugar.DbType type, string ConnString)
        {
            SqlSugarClient db = new SqlSugarClient(
                new ConnectionConfig()
            {
                ConnectionString      = ConnString,
                DbType                = type,                 //设置数据库类型
                IsAutoCloseConnection = true,                 //自动释放数据务,如果存在事务,在事务结束后释放
                InitKeyType           = InitKeyType.Attribute //从实体特性中读取主键自增列信息
            });

            DataTable list = new DataTable();

            if (type == SqlSugar.DbType.MySql)
            {
                list = db.Queryable <Models>().Where(e => e.TABLE_NAME == TableName).ToDataTable();
            }//
            else if (type == SqlSugar.DbType.SqlServer)
            {
                list = db.Queryable <INFORMATION_SCHEMA>().Where(e => e.TABLE_NAME == TableName).ToDataTable();
                list.Columns["CHARACTER_MAXIMUM_LENGTH"].ColumnName = "COLUMN_TYPE";
            }
            return(JsonConvert.SerializeObject(list));
        }
Beispiel #12
0
        private object GetMethodValue(string name, MethodCallExpressionModel model)
        {
            if (IsExtMethod(name))
            {
                model.Expression     = this.Expression;
                model.BaseExpression = this.BaseParameter.CurrentExpression;
                DbType type = DbType.SqlServer;
                if (this.Context is SqlServerExpressionContext)
                {
                    type = DbType.SqlServer;
                }
                else if (this.Context is MySqlExpressionContext)
                {
                    type = DbType.MySql;
                }
                else if (this.Context is SqliteExpressionContext)
                {
                    type = DbType.Sqlite;
                }
                else if (this.Context is OracleExpressionContext)
                {
                    type = DbType.Oracle;
                }
                else if (this.Context is PostgreSQLExpressionContext)
                {
                    type = DbType.PostgreSQL;
                }
                return(this.Context.SqlFuncServices.First(it => it.UniqueMethodName == name).MethodValue(model, type, this.Context));
            }
            else
            {
                if (name == "Parse" && TempParseType.IsIn(UtilConstants.GuidType) && model.Args != null && model.Args.Count() > 1)
                {
                    name = "Equals";
                }
                else if (name == "Parse")
                {
                    name = "To" + TempParseType.Name;
                }
                else if (name == "IsNullOrWhiteSpace")
                {
                    name = "IsNullOrEmpty";
                }
                switch (name)
                {
                case "IIF":
                    return(this.Context.DbMehtods.IIF(model));

                case "HasNumber":
                    return(this.Context.DbMehtods.HasNumber(model));

                case "HasValue":
                    return(this.Context.DbMehtods.HasValue(model));

                case "IsNullOrEmpty":
                    return(this.Context.DbMehtods.IsNullOrEmpty(model));

                case "ToLower":
                    return(this.Context.DbMehtods.ToLower(model));

                case "ToUpper":
                    return(this.Context.DbMehtods.ToUpper(model));

                case "Trim":
                    return(this.Context.DbMehtods.Trim(model));

                case "Contains":
                    return(this.Context.DbMehtods.Contains(model));

                case "ContainsArray":
                    if (model.Args[0].MemberValue == null)
                    {
                        var first = this.Context.Parameters.FirstOrDefault(it => it.ParameterName == model.Args[0].MemberName.ObjToString());
                        if (first.HasValue())
                        {
                            model.Args[0].MemberValue = first.Value;
                        }
                    }
                    var caResult = this.Context.DbMehtods.ContainsArray(model);
                    this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[0].MemberName.ObjToString());
                    return(caResult);

                case "ContainsArrayUseSqlParameters":
                    if (model.Args[0].MemberValue == null)
                    {
                        var first = this.Context.Parameters.FirstOrDefault(it => it.ParameterName == model.Args[0].MemberName.ObjToString());
                        if (first.HasValue())
                        {
                            model.Args[0].MemberValue = first.Value;
                        }
                    }
                    model.Data = this.Context.SqlParameterKeyWord + "INP_" + this.Context.ParameterIndex;
                    this.Context.ParameterIndex++;
                    if (model.Args[0].MemberValue.HasValue())
                    {
                        var inValueIEnumerable = (IEnumerable)model.Args[0].MemberValue;
                        int i = 0;
                        foreach (var item in inValueIEnumerable)
                        {
                            this.Context.Parameters.Add(new SugarParameter(model.Data + "_" + i, item));
                            i++;
                        }
                    }
                    var caResult2 = this.Context.DbMehtods.ContainsArrayUseSqlParameters(model);
                    this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[0].MemberName.ObjToString());
                    return(caResult2);

                case "Equals":
                    return(this.Context.DbMehtods.Equals(model));

                case "EqualsNull":
                    return(this.Context.DbMehtods.EqualsNull(model));

                case "DateIsSame":
                    if (model.Args.Count == 2)
                    {
                        return(this.Context.DbMehtods.DateIsSameDay(model));
                    }
                    else
                    {
                        var dsResult = this.Context.DbMehtods.DateIsSameByType(model);
                        this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[2].MemberName.ObjToString());
                        return(dsResult);
                    }

                case "DateAdd":
                    if (model.Args.Count == 2)
                    {
                        return(this.Context.DbMehtods.DateAddDay(model));
                    }
                    else
                    {
                        var daResult = this.Context.DbMehtods.DateAddByType(model);
                        this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[2].MemberName.ObjToString());
                        return(daResult);
                    }

                case "DateValue":
                    var dvResult = this.Context.DbMehtods.DateValue(model);
                    this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[1].MemberName.ObjToString());
                    return(dvResult);

                case "Between":
                    return(this.Context.DbMehtods.Between(model));

                case "StartsWith":
                    return(this.Context.DbMehtods.StartsWith(model));

                case "EndsWith":
                    return(this.Context.DbMehtods.EndsWith(model));

                case "ToInt32":
                    return(this.Context.DbMehtods.ToInt32(model));

                case "ToInt64":
                    return(this.Context.DbMehtods.ToInt64(model));

                case "ToDate":
                    return(this.Context.DbMehtods.ToDate(model));

                case "ToDateTime":
                    return(this.Context.DbMehtods.ToDate(model));

                case "ToTime":
                    return(this.Context.DbMehtods.ToTime(model));

                case "ToString":
                    if (model.Args.Count > 1 && model.Args.Last().MemberValue.ObjToString().IsContainsIn("-", "/", ":", "yy", "ms", "hh"))
                    {
                        return(GeDateFormat(model.Args.Last().MemberValue.ObjToString(), model.Args.First().MemberName.ObjToString()));
                    }
                    Check.Exception(model.Args.Count > 1, "ToString (Format) is not supported, Use ToString().If time formatting can be used it.Date.Year+\"-\"+it.Data.Month+\"-\"+it.Date.Day ");
                    return(this.Context.DbMehtods.ToString(model));

                case "ToVarchar":
                    return(this.Context.DbMehtods.ToVarchar(model));

                case "ToDecimal":
                    return(this.Context.DbMehtods.ToDecimal(model));

                case "ToGuid":
                    return(this.Context.DbMehtods.ToGuid(model));

                case "ToDouble":
                    return(this.Context.DbMehtods.ToDouble(model));

                case "ToBool":
                    return(this.Context.DbMehtods.ToBool(model));

                case "ToBoolean":
                    return(this.Context.DbMehtods.ToBool(model));

                case "Substring":
                    return(this.Context.DbMehtods.Substring(model));

                case "Replace":
                    return(this.Context.DbMehtods.Replace(model));

                case "Length":
                    return(this.Context.DbMehtods.Length(model));

                case "AggregateSum":
                    return(this.Context.DbMehtods.AggregateSum(model));

                case "AggregateAvg":
                    return(this.Context.DbMehtods.AggregateAvg(model));

                case "AggregateMin":
                    return(this.Context.DbMehtods.AggregateMin(model));

                case "AggregateMax":
                    return(this.Context.DbMehtods.AggregateMax(model));

                case "AggregateCount":
                    return(this.Context.DbMehtods.AggregateCount(model));

                case "AggregateDistinctCount":
                    return(this.Context.DbMehtods.AggregateDistinctCount(model));

                case "MappingColumn":
                    var mappingColumnResult = this.Context.DbMehtods.MappingColumn(model);
                    var isValid             = model.Args[0].IsMember && model.Args[1].IsMember == false;
                    //Check.Exception(!isValid, "SqlFunc.MappingColumn parameters error, The property name on the left, string value on the right");
                    this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[1].MemberName.ObjToString());
                    if (mappingColumnResult == "")
                    {
                        return(model.Args[1].MemberName.ObjToString().TrimStart('\'').TrimEnd('\''));
                    }
                    return(mappingColumnResult);

                case "IsNull":
                    return(this.Context.DbMehtods.IsNull(model));

                case "MergeString":
                    return(this.Context.DbMehtods.MergeString(model.Args.Select(it => it.MemberName.ObjToString()).ToArray()));

                case "SelectAll":
                case "GetSelfAndAutoFill":
                    this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[0].MemberName.ObjToString());
                    return(this.Context.DbMehtods.GetSelfAndAutoFill(model.Args[0].MemberValue.ObjToString(), this.Context.IsSingle));

                case "GetDate":
                    return(this.Context.DbMehtods.GetDate());

                case "GetRandom":
                    return(this.Context.DbMehtods.GetRandom());

                case "CharIndex":
                    return(this.Context.DbMehtods.CharIndex(model));

                case "BitwiseAnd":
                    return(this.Context.DbMehtods.BitwiseAnd(model));

                case "BitwiseInclusiveOR":
                    return(this.Context.DbMehtods.BitwiseInclusiveOR(model));

                case "ToDateShort":
                    return(this.Context.DbMehtods.ToDateShort(model));

                case "Oracle_ToChar":
                    return(this.Context.DbMehtods.Oracle_ToChar(model));

                case "Oracle_ToDate":
                    return(this.Context.DbMehtods.Oracle_ToDate(model));

                case "SqlServer_DateDiff":
                    return(this.Context.DbMehtods.SqlServer_DateDiff(model));

                case "Format":
                    var xx     = base.BaseParameter;
                    var result = this.Context.DbMehtods.Format(model);
                    this.Context.Parameters.RemoveAll(it => model.Args.Select(x => x.MemberName.ObjToString()).Contains(it.ParameterName));
                    return(result);

                default:
                    break;
                }
            }
            return(null);
        }
Beispiel #13
0
        private void btnSaveRetVal_Click(object sender, EventArgs e)
        {
            if (skinLVMethods.SelectedItems.Count > 0 && skinLVInterfaces.SelectedItems.Count > 0)
            {
                try
                {
                    var       a         = skinLVMethods.SelectedItems[0];
                    var       intf      = skinLVInterfaces.SelectedItems[0];
                    HA_Method ha_method = new HA_Method
                    {
                        intf_code = a.SubItems[0].Text,
                        m_name    = a.SubItems[1].Text,
                        m_code    = a.SubItems[2].Text,
                        m_desc    = a.SubItems[3].Text,
                        //m_reqtype = a.SubItems[4].Text,
                        m_template     = Convert.ToInt32(a.SubItems[4].Text),
                        m_version      = a.SubItems[5].Text,
                        m_funcode      = a.SubItems[6].Text,
                        m_isencrypted  = false, //a.SubItems[2].Text,
                        m_arggrpcode   = a.SubItems[8].Text,
                        m_rtnvaluecode = a.SubItems[9].Text,
                        m_pagesize     = Convert.ToInt32(a.SubItems[10].Text)
                    };
                    //1.connStr: 通过intf_code得到 interface上的dbConn,取出connStr和DBType
                    string    connStr  = "";
                    string    connName = "";
                    string    dbType   = "";
                    string    intfcode = ha_method.intf_code;
                    DbService db       = DB.GetMainDb();
                    Hashtable htPara   = new Hashtable();
                    htPara.Add("intf_code", intfcode);
                    DataSet tempds = db.ExecuteSqlID("GetInterface2", htPara);
                    if (tempds != null && tempds.Tables.Count > 0)
                    {
                        if (tempds.Tables[0].Rows.Count > 0)
                        {
                            connName = tempds.Tables[0].Rows[0]["intf_dbconn"].ToString();
                        }
                    }
                    if (string.IsNullOrEmpty(connName))
                    {
                        MessageBox.Show("接口没有配置数据库连接");
                        return;
                    }
                    //2.dt
                    SqlSugar.DbType sdt        = SqlSugar.DbType.SqlServer;
                    Hashtable       htParaConn = new Hashtable();
                    htParaConn.Add("conn_name", connName);
                    tempds = db.ExecuteSqlID("GetConnection2", htParaConn);

                    if (tempds != null && tempds.Tables.Count > 0)
                    {
                        if (tempds.Tables[0].Rows.Count > 0)
                        {
                            connStr = tempds.Tables[0].Rows[0]["conn_string"].ToString();
                            dbType  = tempds.Tables[0].Rows[0]["conn_dbtype"].ToString();
                        }
                    }
                    if (string.IsNullOrEmpty(connStr))
                    {
                        MessageBox.Show("数据库连接不存在");
                        return;
                    }
                    switch (dbType)
                    {
                    case "MSSql":
                        sdt = SqlSugar.DbType.SqlServer;
                        break;

                    case "Cache*":

                        break;

                    case "Oracle*":
                        sdt = SqlSugar.DbType.Oracle;
                        break;

                    default:
                        break;
                    }
                    //3.sqlStmt
                    string sqlStmt = ha_method.m_funcode;
                    if (string.IsNullOrEmpty(sqlStmt))
                    {
                        MessageBox.Show("没有查询语句");
                        return;
                    }
                    //4.paras 从ag_code里得到 ag组,再去得到所有的参数
                    string    ag_code  = ha_method.m_arggrpcode;
                    Hashtable htParaAG = new Hashtable();
                    htParaAG.Add("ag_code", ag_code);
                    tempds = db.ExecuteSqlID("GetParas2", htParaAG);
                    List <SugarParameter> sParas = new List <SugarParameter>();

                    if (tempds != null && tempds.Tables.Count > 0)
                    {
                        if (tempds.Tables[0].Rows.Count > 0)
                        {
                            int rowCount = tempds.Tables[0].Rows.Count;

                            for (int i = 0; i < rowCount; i++)
                            {
                                SugarParameter sp = new SugarParameter(tempds.Tables[0].Rows[i]["para_name"].ToString(), tempds.Tables[0].Rows[i]["para_default"].ToString());
                                sParas.Add(sp);
                            }
                        }
                    }
                    if (sParas.Count == 0)
                    {
                        MessageBox.Show("没有配置参数");
                        return;
                    }
                    //5 处理pagesize
                    if (!sqlStmt.ToLower().Contains("top"))
                    {
                        if (ha_method.m_pagesize == 0)
                        {
                            sqlStmt = sqlStmt.ToLower().Replace("select", "select top 1");
                        }
                        else
                        {
                            string topnumber = ha_method.m_pagesize.ToString();
                            if (ha_method.m_pagesize > 5)
                            {
                                topnumber = "5";
                            }
                            sqlStmt = sqlStmt.ToLower().Replace("select", "select top " + topnumber);
                        }
                    }
                    string   resultJSON = SqlSugarUtils.GetSingleJSONResult(connStr, sdt, sqlStmt, sParas);
                    JsonTool jt         = new JsonTool();
                    //6 美化JSON字符串
                    resultJSON   = jt.ConvertJsonString(resultJSON);
                    edtJson.Text = resultJSON;
                    //7 顺便保存到 RetVO 的 类JSON里去
                    Hashtable htParaRV = new Hashtable();
                    htParaRV.Add("rv_name", "ret" + ha_method.m_code);
                    tempds = db.ExecuteSqlID("GetRetVO2", htParaRV);
                    if (tempds != null && tempds.Tables.Count > 0)
                    {
                        HA_RetValObjectDAL dal = new HA_RetValObjectDAL();
                        HA_RetValObject    rvo = new HA_RetValObject
                        {
                            rv_name    = "ret" + ha_method.m_code,
                            rv_exttype = tempds.Tables[0].Rows[0]["rv_exttype"].ToString(),
                            rv_note    = tempds.Tables[0].Rows[0]["rv_note"].ToString(),
                            rv_JSON    = resultJSON
                        };
                        bool ret = dal.Update(rvo);
                        if (ret == false)
                        {
                            MessageBox.Show("保存到RetVO失败 : " + ret);
                        }
                    }
                    //8 顺手将json转换为类文件
                    #region 测试后屏蔽这段代码
                    //string destFolder = System.AppDomain.CurrentDomain.BaseDirectory;
                    //destFolder += ha_method.intf_code + @"\" + ha_method.m_code + @"\Model";
                    //DirectoryInfo di = new DirectoryInfo(destFolder);
                    //if (di.Exists == false)
                    //{
                    //    Directory.CreateDirectory(destFolder);
                    //}

                    //bool writeClassRet = RunTimeHelper.GenClassStringByJSON(resultJSON, "ILAK.API", "ILAK.API.Model", destFolder, "ret" + ha_method.m_code);

                    //if (!writeClassRet)
                    //{
                    //    MessageBox.Show("写文件失败");
                    //}
                    #endregion
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Beispiel #14
0
        private void btnTestConn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtConnStrGen.Text))
            {
                try
                {
                    if (skinLVConns.SelectedItems.Count > 0)
                    {
                        labelConnStatus.Text = "";
                        var             a            = skinLVConns.SelectedItems[0];
                        string          testConnStr  = txtConnStrGen.Text;
                        string          DataBaseType = a.SubItems[5].Text;
                        SqlSugar.DbType sdt          = SqlSugar.DbType.SqlServer;
                        switch (DataBaseType)
                        {
                        case "MSSql":
                            sdt = SqlSugar.DbType.SqlServer;
                            break;

                        case "Cache*":

                            break;

                        case "Oracle*":
                            sdt = SqlSugar.DbType.Oracle;
                            break;

                        default:
                            break;
                        }
                        using (SqlSugarClient ssc = SqlSugarUtils.GetDb(testConnStr, sdt))
                        {
                            List <DbColumnInfo> columns = new List <DbColumnInfo>();
                            DbColumnInfo        column  = new DbColumnInfo();
                            column.DataType     = "varchar";
                            column.DbColumnName = "testcol";
                            column.Length       = 50;
                            columns.Add(column);
                            bool result = ssc.DbMaintenance.CreateTable("HydTestDbTable", columns);
                            if (result)
                            {
                                ssc.DbMaintenance.DropTable("HydTestDbTable");
                                labelConnStatus.Text = "测试成功!";
                            }
                            else
                            {
                                labelConnStatus.Text = "连接失败!";
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    labelConnStatus.Text = "连接失败! " + ex.Message;
                }
            }
            else
            {
                MessageBox.Show("请先 生成连接字符串");
            }
        }
Beispiel #15
0
        private List <EntitiesGen> GetGenList(List <CodeTable> tableList, List <CodeType> types, SqlSugar.DbType databasedbType)
        {
            List <EntitiesGen> result = new List <EntitiesGen>();
            var mapping = Db.Queryable <MappingProperty>().ToList();
            var tags    = Db.Queryable <TagProperty>().ToList();

            if (databasedbType == DbType.MySql)
            {
                var timestamp = types.FirstOrDefault(it => it.Name == "timestamp");
                if (timestamp != null)
                {
                    timestamp.CSharepType = "DateTime";
                }
            }
            foreach (var item in tableList)
            {
                EntitiesGen gen = new EntitiesGen()
                {
                    ClassName    = item.ClassName,
                    Description  = item.Description,
                    TableName    = item.TableName,
                    PropertyGens = new List <PropertyGen>()
                };
                foreach (var column in base.CodeColumnsDb.GetList(it => it.CodeTableId == item.Id))
                {
                    var codeType = types.First(it => it.Name == column.CodeType);
                    if (codeType.Id == 3)
                    {
                        PropertyGen proGen = new PropertyGen()
                        {
                            DbColumnName  = column.DbColumnName,
                            Description   = column.Description,
                            IsIdentity    = column.IsIdentity,
                            IsPrimaryKey  = column.IsPrimaryKey,
                            PropertyName  = GetPropertyName(column.ClassProperName),
                            Type          = GetType(column),
                            IsNullable    = column.Required == false,
                            DbType        = "",
                            Length        = 0,
                            DecimalDigits = 0,
                            IsIgnore      = true,
                            CodeType      = column.CodeType,
                            DefaultValue  = column.DefaultValue
                        };
                        var mappings = mapping.Where(it => item.DbId == it.DbId && it.TableName == item.ClassName && it.ColumnName == column.ClassProperName).ToList();;
                        proGen.MappingProperties = tags.Where(it => mappings.Any(x => x.TagId == it.Id + "")).ToList();
                        gen.PropertyGens.Add(proGen);
                    }
                    else
                    {
                        var         dbType = GetTypeInfoByDatabaseType(codeType.DbType, databasedbType);
                        PropertyGen proGen = new PropertyGen()
                        {
                            DbColumnName  = column.DbColumnName,
                            Description   = column.Description,
                            IsIdentity    = column.IsIdentity,
                            IsPrimaryKey  = column.IsPrimaryKey,
                            PropertyName  = GetPropertyName(column.ClassProperName),
                            Type          = IsSpecialType(column) ? GetType(column) : codeType.CSharepType,
                            IsNullable    = column.Required == false,
                            DbType        = dbType.Name,
                            Length        = dbType.Length,
                            DecimalDigits = dbType.DecimalDigits,
                            IsSpecialType = IsSpecialType(column),
                            CodeType      = column.CodeType,
                            DefaultValue  = column.DefaultValue
                        };
                        var mappings = mapping.Where(it => item.DbId == it.DbId && it.TableName == item.ClassName && it.ColumnName == column.ClassProperName).ToList();;
                        proGen.MappingProperties = tags.Where(it => mappings.Any(x => x.TagId == it.Id + "")).ToList();
                        gen.PropertyGens.Add(proGen);
                    }
                }
                result.Add(gen);
            }
            return(result);
        }
Beispiel #16
0
 /// <summary>
 /// 功能描述:设置初始化参数
 /// zjg
 /// </summary>
 /// <param name="strConnectionString">连接字符串</param>
 /// <param name="enmDbType">数据库类型</param>
 public static void Init(string strConnectionString, DbType enmDbType = SqlSugar.DbType.SqlServer)
 {
     _connectionString = strConnectionString;
     _dbType           = enmDbType;
 }
Beispiel #17
0
 /// <summary>
 /// 获得SqlSugarClient(使用该方法, 默认请手动释放资源, 如using(var db = SugarBase.GetIntance()){你的代码}, 如果把isAutoCloseConnection参数设置为true, 则无需手动释放, 会每次操作数据库释放一次, 可能会影响性能, 请自行判断使用)
 /// </summary>
 /// <param name="commandTimeOut">等待超时时间, 默认为30秒 (单位: 秒)</param>
 /// <param name="dbType">数据库类型, 默认为SQL Server</param>
 /// <param name="isAutoCloseConnection">是否自动关闭数据库连接, 默认不是, 如果设置为true, 则会在每次操作完数据库后, 即时关闭, 如果一个方法里面多次操作了数据库, 建议保持为false, 否则可能会引发性能问题</param>
 /// <returns></returns>
 public static SqlSugarClient GetIntance(int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql, bool isAutoCloseConnection = false)
 {
     return(InitDB(commandTimeOut, dbType, isAutoCloseConnection));
 }
Beispiel #18
0
 /// <summary>
 /// 带事务处理的执行数据库操作
 /// </summary>
 /// <typeparam name="Result">返回值类型 泛型</typeparam>
 /// <param name="func">方法委托</param>
 /// <param name="commandTimeOut">超时时间, 单位为秒, 默认为30秒</param>
 /// <param name="dbType">数据库类型</param>
 /// <returns>泛型返回值</returns>
 public static Result ExecTran <Result>(Func <SqlSugarClient, Result> func, int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql)
 {
     if (func == null)
     {
         throw new Exception("委托为null, 事务处理无意义");
     }
     using (var db = InitDB(commandTimeOut, dbType))
     {
         try
         {
             db.Ado.BeginTran(IsolationLevel.Unspecified);
             var result = func(db);
             db.Ado.CommitTran();
             return(result);
         }
         catch (Exception ex)
         {
             db.Ado.RollbackTran();
             NLogger.Error(ex);
             throw ex;
         }
         finally
         {
             db.Dispose();
         }
     }
 }
Beispiel #19
0
 /// <summary>
 /// 执行数据库操作
 /// </summary>
 /// <typeparam name="Result">返回值类型 泛型</typeparam>
 /// <param name="func">方法委托</param>
 /// <param name="commandTimeOut">超时时间, 单位为秒, 默认为30秒</param>
 /// <param name="dbType">数据库类型</param>
 /// <returns>泛型返回值</returns>
 public static Result Exec <Result>(Func <SqlSugarClient, Result> func, int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql)
 {
     if (func == null)
     {
         throw new Exception("委托为null, 事务处理无意义");
     }
     using (var db = InitDB(commandTimeOut, dbType))
     {
         try
         {
             return(func(db));
         }
         catch (Exception ex)
         {
             NLogger.Error(ex);
             throw ex;
         }
         finally
         {
             db.Dispose();
         }
     }
 }
Beispiel #20
0
 /// <summary>
 /// 功能描述:设置初始化参数
 /// 作  者:Blog.Core
 /// </summary>
 /// <param name="strConnectionString">连接字符串</param>
 /// <param name="enmDbType">数据库类型</param>
 public static void Init(string strConnectionString, DbType enmDbType = DbType.MySql)
 {
     ConnectionString = strConnectionString;
     DbType           = enmDbType;
 }