public object ExecuteScalar(BaseQuery q) { string message = "SQL语句:" + q.CommandText + ";Parameters:{"; if (q.Parameters != null) { for (int i = 0; i < q.Parameters.Count; i++) { message += "\"" + q.Parameters[i].ParameterName + "\"" + ":"; message += "\"" + q.Parameters[i].Value + "\"" + ";"; } } message += "}"; try { LogService.Default.Info(message); IDbCommand sqlCommand = DbProvider.GetDbCommand(this.dbtype); this.PrepareCommand(sqlCommand, q); object result = sqlCommand.ExecuteScalar(); this.SyncParameter(sqlCommand, q); sqlCommand.Parameters.Clear(); return(result); } catch (Exception e) { LogService.Default.Fatal(e); LogService.Default.Fatal((message + "\n" + Assembly.GetExecutingAssembly().Location.ToLower())); throw e; } }
private static Int32 GetSubmit(BaseQuery o, string targetdb, out Exception outex) { //先判断是否是新增,如果不是新增就修改 outex = null; o.Convert(targetdb); Int32 affectedCount = -1; try { if (o.excutParBag.excutEnum == ExcutEnum.Insert && ((ExcutParBag_Insert)o.excutParBag).isOutIdentity) { affectedCount = DataAccess.ExecuteScalarToWriterOnlyForInsertRentrunIdentity(o, o.databaseProperty).ToSafeInt32(-1); } else { affectedCount = DataAccess.ExecuteNonQuery(o, o.databaseProperty).ToSafeInt32(-1); } } catch (Exception ex) { outex = ex; LogService.Default.Fatal("执行失败:" + ex.Message, ex); affectedCount = -1; } finally { } return(affectedCount); }
public DataSet ExecuteDataset(BaseQuery q) { string message = "SQL语句:" + q.CommandText + ";Parameters:{"; if (q.Parameters != null) { for (int i = 0; i < q.Parameters.Count; i++) { message += "\"" + q.Parameters[i].ParameterName + "\"" + ":"; message += "\"" + q.Parameters[i].Value + "\"" + ";"; } } message += "}"; try { LogService.Default.Info(message); DataSet dataSet = new DataSet(); IDbCommand sqlCommand = DbProvider.GetDbCommand(this.dbtype); this.PrepareCommand(sqlCommand, q); IDbDataAdapter sqlDataAdapter = DbProvider.GetDbDataAdapter(dbtype, sqlCommand); sqlDataAdapter.Fill(dataSet); this.SyncParameter(sqlCommand, q); sqlCommand.Parameters.Clear(); return(dataSet); } catch (Exception e) { LogService.Default.Fatal(message + "\n" + Assembly.GetExecutingAssembly().Location.ToLower()); LogService.Default.Fatal(e); throw e; } }
public static XmlReader ExecuteXmlReader(BaseQuery q, DatabaseProperty dp) { DataAccess sqlDataAccess = new DataAccess(dp.Reader.ConnectionString, dp.Reader.DatabaseType); sqlDataAccess.Open(); return(sqlDataAccess.ExecuteXmlReader(q)); }
public static int ExecuteNonQuery(BaseQuery q, DatabaseProperty dp) { string message = "SQL语句:" + q.CommandText + ";Parameters:{"; if (q.Parameters != null) { for (int i = 0; i < q.Parameters.Count; i++) { message += "\"" + q.Parameters[i].ParameterName + "\"" + ":"; message += "\"" + q.Parameters[i].Value + "\"" + ";"; } } message += "}"; try { LogService.Default.Info(message); DataAccess sqlDataAccess = new DataAccess(dp.Writer.ConnectionString, dp.Writer.DatabaseType); sqlDataAccess.Open(); int result = sqlDataAccess.ExecuteNonQuery(q); sqlDataAccess.Close(); return(result); } catch (Exception e) { LogService.Default.Fatal(e); LogService.Default.Fatal((message + "\n" + Assembly.GetExecutingAssembly().Location.ToLower())); throw e; } }
private static object ExecuteScalar(BaseQuery q, DataAccess da) { da.Open(); object result = da.ExecuteScalar(q); da.Close(); return(result); }
public bool TransationBulkCopy(DataAccess dataAccess, IDbConnection connection, IDbTransaction dbTransaction, List <DataTable> dtList, bool bl) { //处理大批量语句 if (dtList != null && dtList.Count > 0 && bl) { foreach (var item in dtList) { if (item != null && item.Rows.Count > 0) { StringBuilder sb = new StringBuilder(); sb.Append("INSERT INTO " + item.TableName + "("); for (int i = 0; i < item.Columns.Count; i++) { sb.Append(item.Columns[i].ColumnName + ","); } sb.Remove(sb.ToString().LastIndexOf(','), 1); sb.Append(") VALUES "); for (int i = 0; i < item.Rows.Count; i++) { sb.Append("("); for (int j = 0; j < item.Columns.Count; j++) { sb.Append("'" + item.Rows[i][j] + "',"); } sb.Remove(sb.ToString().LastIndexOf(','), 1); sb.Append("),"); } sb.Remove(sb.ToString().LastIndexOf(','), 1); sb.Append(";"); BaseQuery sql = new BaseQuery(); sql.CommandText = sb.ToString(); int res = -1; try { res = dataAccess.ExecuteNonQuery(sql); } catch (Exception ex) { res = -1; // Unknown column 'names' in 'field list' LogService.Default.Fatal("操作失败!" + ex.Message.Replace("Unknown column", "未知列").Replace("in 'field list'", "存在字段集合中!")); } if (res >= 0) { return(true); } else { return(false); } } } } return(bl); }
public static XmlDocument ExecuteXmlDoc(BaseQuery q, DatabaseProperty dp) { DataAccess sqlDataAccess = new DataAccess(dp.Reader.ConnectionString, dp.Reader.DatabaseType); sqlDataAccess.Open(); XmlDocument result = sqlDataAccess.ExecuteXmlDoc(q); sqlDataAccess.Close(); return(result); }
public XmlReader ExecuteXmlReader(BaseQuery q) { SqlCommand sqlCommand = (SqlCommand)DbProvider.GetDbCommand(this.dbtype); this.PrepareCommand(sqlCommand, q); XmlReader result = sqlCommand.ExecuteXmlReader(); this.SyncParameter(sqlCommand, q); sqlCommand.Parameters.Clear(); return(result); }
public static object ExecuteScalar(BaseQuery q, DatabaseProperty dp, bool isWritable) { DataAccess da; if (isWritable) { da = new DataAccess(dp.Writer.ConnectionString, dp.Writer.DatabaseType); } else { da = new DataAccess(dp.Reader.ConnectionString, dp.Reader.DatabaseType); } return(DataAccess.ExecuteScalar(q, da)); }
internal static bool Excut(this BaseQuery o) { o.Convert(o.Targetdb); int i = DataAccess.ExecuteNonQuery(o, o.databaseProperty); if (i >= 0) { return(true); } else { return(false); } }
internal static void SelectPageData(BaseQuery baseQuery) { var bag = ((ExcutParBag_Page)(baseQuery).excutParBag); baseQuery.CommandText = string.Empty; baseQuery.Parameters.Clear(); if (bag._pageMode == PageMode.SelectCount) { GetPageDataBySelect(baseQuery); } else { GetPageDataByCount(baseQuery); } }
/// <summary> /// 查询数据 /// </summary> /// <param name="property"></param> /// <returns></returns> internal static DataTable ReturnDataTable(this BaseQuery o, int tableIndex = 0) { o.Convert(o.Targetdb); DataSet Ds = DataAccess.ExecuteDataset(o, o.databaseProperty); if (Ds != null && Ds.Tables.Count > 0) { if (tableIndex > 0) { return(Ds.Tables[tableIndex]); } else { return(Ds.Tables[0]); } } return(null); }
//关键代码 转换实体,用于支持多数据库类型的操作 internal void Convert(string targetdb) { try { this.SetTargetDb(targetdb); qQeryy = this.MapToExutQuery(); } catch (Exception ex) { LogService.Default.Fatal( "core 映射失败:" + "执行类型:" + this.excutParBag.excutEnum.ToString() + "异常信息:" + ex.Message + "TableName:" + this.excutParBag.tableName + ";" + "|Stack:" + ex.StackTrace); throw ex; } try { qQeryy.SetCommadText(); //构建对应的SQL语句 this.Parameters = qQeryy.Parameters; this.CommandText = qQeryy.CommandText; } catch (Exception ex) { LogService.Default.Fatal( "构建SQL语句出错:" + "执行类型:" + this.excutParBag.excutEnum.ToString() + "异常信息:" + ex.Message + "TableName:" + this.excutParBag.tableName + ";" + "|Stack:" + ex.StackTrace); } }
internal static BaseQuery MapToExutQuery(this BaseQuery o) { BaseQuery vdb = new BaseQuery(); switch (o.databaseType) { case DatabaseType.MSSQLServer: vdb = o.MapTo <MsSqlQuery>(new Action <AutoMapper.IMapperConfigurationExpression>(cfg => { cfg.ShouldMapProperty = pi => pi.CanWrite; })); break; case DatabaseType.MySql: vdb = o.MapTo <MySqlQuery>(new Action <AutoMapper.IMapperConfigurationExpression>(cfg => { cfg.ShouldMapProperty = pi => pi.CanWrite; })); break; default: vdb = o.MapTo <MsSqlQuery>(new Action <AutoMapper.IMapperConfigurationExpression>(cfg => { cfg.ShouldMapProperty = pi => pi.CanWrite; })); break; } return(vdb); }
private void PrepareCommand(IDbCommand cmd, BaseQuery q) { cmd.CommandType = q.CommandType; cmd.CommandText = q.CommandText; cmd.Connection = this.m_Connection; cmd.CommandTimeout = q.CommandTimeout; cmd.Transaction = this.m_Trans; if (q.CommandType == CommandType.Text) { //if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null) //{ // string text = HttpContext.Current.Request.Url.ToString(); // if (text.Contains("?")) // { // text = text.Remove(text.IndexOf("?")); // } // cmd.CommandText = cmd.CommandText + "/* URL:" + text + " */"; //} //else //{ // cmd.CommandText = cmd.CommandText + "/* Location:" + Assembly.GetExecutingAssembly().Location.ToLower() + " */"; //} cmd.CommandText = cmd.CommandText + "/* Location:" + Assembly.GetExecutingAssembly().Location.ToLower() + " */"; } if (q.Parameters.Count > 0) { int count = q.Parameters.Count; for (int i = 0; i < count; i++) { var par = cmd.CreateParameter(); par.ParameterName = q.Parameters[i].ParameterName; par.Size = q.Parameters[i].Size; par.Value = q.Parameters[i].Value; par.Direction = q.Parameters[i].Direction; par.DbType = q.Parameters[i].DbType;//Utils.SqlTypeToDbType( q.Parameters[i].SqlDbType); cmd.Parameters.Add(par); } } }
public static BaseQuery ConvertOneQuery(this List <BaseQuery> list) { StringBuilder builder = new StringBuilder(); SqlQueryParameterCollection lp = new SqlQueryParameterCollection(); Int32 index = 0; try { list.ForEach(sq => { builder.Append("\n---------SQL语句-------\n"); for (Int32 i = 0; i < sq.Parameters.Count; i++) { var parmName = "@sp" + index.ToString(); var orParmName = sq.Parameters[i].ParameterName; if (orParmName.IndexOf("@") == -1) { orParmName = "@" + orParmName; } var parm = sq.Parameters[i]; sq.CommandText = sq.CommandText.Replace(orParmName, parmName); parm.ParameterName = parmName; lp.Add(parm); index++; } builder.Append(sq.CommandText); builder.Append(";"); }); BaseQuery q = new BaseQuery(); q.CommandText = builder.ToString(); q.Parameters = lp; return(q); } catch (Exception ex) { throw ex; } }
/// <summary> /// 实例化数据 /// </summary> void InitCommadInfo() { bool bl = true; if (_list == null || _list.Count == 0) { bl = true; } else { try { BaseQuery q = _list.ConvertOneQuery(); finalSqlQuery = q; _comaCommandInfo.Parameters = q.Parameters; _comaCommandInfo.SqlCommand = q.CommandText; } catch (Exception ex) { DistributedEx = ex; LogService.Default.Fatal("处理事务语句时出现异常:" + ex.Message); } } }
/// <summary> /// 提交到数据库执行,成功:返回受影响的行数,如果执行不成功,返回-1 /// </summary> /// <param name="o">执行的SqlQuery:成功:返回受影响的行数,如果执行不成功,返回-1</param> /// <returns>返回受影响的行数</returns> public static Int32 Submit(this BaseQuery o, string targetdb) { Exception ex = null; return(GetSubmit(o, targetdb, out ex)); }
private static void GetPageDataByCount(BaseQuery baseQuery) { var bag = (ExcutParBag_Page)(baseQuery.excutParBag); var sql = string.Empty; var selectTable = bag.pageTableName; var selectColumns = bag.pageColumns; var len = bag.commandText.ToLower().IndexOf("select") + 6; baseQuery.SetDynamicParameters((bag.dynamics)); BaseQuery sqlTemp = new BaseQuery(); sqlTemp.CommandText = bag.commandText; sqlTemp.CommandType = CommandType.Text; for (int i = 0; i < baseQuery.Parameters.Count; i++) { SqlParameter sqlpa = baseQuery.Parameters[i]; SqlParameter par = new SqlParameter(); par.DbType = sqlpa.DbType; par.Direction = sqlpa.Direction; par.ParameterName = sqlpa.ParameterName; par.Value = sqlpa.Value; sqlTemp.Parameters.Add(par); } if (!bag.isPage) { bag.pageIndex = 1; bag.pageSize = 1; } if (bag.pageIndex == 1) { #region //最新改动 sqlTemp.CommandText = sqlTemp.CommandText.Insert(len, " TOP(@num) COUNT(0) over() CHEOKTOTALCOUNT,"); if (!string.IsNullOrEmpty(bag.whereBuiler.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.whereBuiler.ToString()) ? string.Empty : string.Format(" WHERE {0} ", bag.whereBuiler.ToString())); } if (!string.IsNullOrEmpty(bag.orderBy.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.orderBy.ToString()) ? string.Empty : string.Format(" ORDER BY {0} ", bag.orderBy.ToString())); } #endregion sqlTemp.Parameters.Add("@num", bag.pageSize, SqlDbType.Int, 4); } else { sqlTemp.CommandText = sqlTemp.CommandText.Insert(len, string.Format(" ROW_NUMBER() OVER(ORDER BY {0}) as [num] ,COUNT(0) over() CHEOKTOTALCOUNT, ", string.IsNullOrEmpty(bag.orderBy.ToString()) ? "(SELECT 0)" : bag.orderBy.ToString())); if (!string.IsNullOrEmpty(bag.whereBuiler.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.whereBuiler.ToString()) ? string.Empty : string.Format(" WHERE {0} ", bag.whereBuiler.ToString())); } sqlTemp.CommandText = "SELECT * FROM (" + sqlTemp.CommandText + ") as [tab] where [num] between @Start and @End"; sqlTemp.Parameters.Add("@Start", ((bag.pageIndex - 1) * bag.pageSize + 1), SqlDbType.Int, 4); sqlTemp.Parameters.Add("@End", (bag.pageIndex * bag.pageSize), SqlDbType.Int, 4); } try { if (!string.IsNullOrEmpty(bag._preWith)) { sqlTemp.CommandText = bag._preWith + @" --With 子句已经完毕 " + sqlTemp.CommandText; } baseQuery.CommandText = sqlTemp.CommandText; baseQuery.Parameters = sqlTemp.Parameters; } finally { } }
private static void GetPageDataBySelect(BaseQuery baseQuery) { //SET @a = 0; //select(@a:= count(0)) as cheokcount from t_user; //select *,@a as cheokcount from T_User limit 1,10; var bag = (ExcutParBag_Page)(baseQuery.excutParBag); var sql = string.Empty; var selectTable = bag.pageTableName; var selectColumns = bag.pageColumns; var len = bag.commandText.ToLower().IndexOf(" from") + 1; baseQuery.SetDynamicParameters((bag.dynamics)); BaseQuery sqlTemp = new BaseQuery(); sqlTemp.CommandText = bag.commandText; sqlTemp.CommandType = CommandType.Text; for (int i = 0; i < baseQuery.Parameters.Count; i++) { SqlParameter sqlpa = baseQuery.Parameters[i]; SqlParameter par = new SqlParameter(); par.DbType = sqlpa.DbType; par.Direction = sqlpa.Direction; par.ParameterName = sqlpa.ParameterName; par.Value = sqlpa.Value; sqlTemp.Parameters.Add(par); } //构建取总数的数据 StringBuilder sqlReal = new StringBuilder(); sqlReal.AppendLine("/*******查询TotalCount*******/"); //sqlReal.AppendLine("SET @totalcountcheok=0;"); sqlReal.AppendLine("select"); sqlReal.AppendLine("(@totalcountcheok:= count(0))"); sqlReal.AppendLine("from"); sqlReal.AppendLine(selectTable); if (!string.IsNullOrEmpty(bag.whereBuiler.ToString())) { sqlReal = sqlReal.AppendLine(string.IsNullOrWhiteSpace(bag.whereBuiler.ToString()) ? string.Empty : string.Format(" WHERE {0}; ", bag.whereBuiler.ToString())); } else { sqlReal.Append(";"); } sqlReal.AppendLine("/*******SQL查询数据*******/"); sqlReal.AppendLine(""); if (!bag.isPage) { bag.pageIndex = 1; bag.pageSize = 1; } if (bag.pageIndex == 1) { #region //最新改动 sqlTemp.CommandText = sqlTemp.CommandText.Insert(len, ",@totalcountcheok as CHEOKTOTALCOUNT "); if (!string.IsNullOrEmpty(bag.whereBuiler.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.whereBuiler.ToString()) ? string.Empty : string.Format(" WHERE {0} ", bag.whereBuiler.ToString())); } if (!string.IsNullOrEmpty(bag.orderBy.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.orderBy.ToString()) ? string.Empty : string.Format(" ORDER BY {0} ", bag.orderBy.ToString())); } sqlTemp.CommandText = sqlTemp.CommandText + " LIMIT " + "0" + "," + bag.pageSize; #endregion } else { sqlTemp.CommandText = sqlTemp.CommandText.Insert(len, ",@totalcountcheok as CHEOKTOTALCOUNT "); if (!string.IsNullOrEmpty(bag.whereBuiler.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.whereBuiler.ToString()) ? string.Empty : string.Format(" WHERE {0} ", bag.whereBuiler.ToString())); } if (!string.IsNullOrEmpty(bag.orderBy.ToString())) { sqlTemp.CommandText = sqlTemp.CommandText + (string.IsNullOrWhiteSpace(bag.orderBy.ToString()) ? string.Empty : string.Format(" ORDER BY {0} ", bag.orderBy.ToString())); } sqlTemp.CommandText = sqlTemp.CommandText + " LIMIT " + (((bag.pageIndex - 1) * bag.pageSize) - 1) + "," + bag.pageSize; } try { sqlTemp.CommandText = sqlReal.ToString() + sqlTemp.CommandText; if (!string.IsNullOrEmpty(bag._preWith)) { sqlTemp.CommandText = bag._preWith + @" /**With 子句已经完毕**/ " + sqlTemp.CommandText; } //sqlTemp.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = "@totalcountcheok", ParameterName= "@totalcountcheok" }); baseQuery.CommandText = sqlTemp.CommandText; baseQuery.Parameters = sqlTemp.Parameters; } finally { } }
/// <summary> /// 执行的SqlQuery:成功:返回受影响的行数,如果执行不成功,返回-1;如果是执行的是新增提交:模型中主键为自增长IDENTITY时,成功返回新增主键ID, 不成功 则返回-1; 当新增模型主键是非自增长ID时:成功返回 1 ,不成功返回 -1; /// </summary> /// <param name="o">执行的SQL</param> /// <returns>返回受影响的行数</returns> public static Int32 Submit(this BaseQuery o) { Exception ex = null; return(GetSubmit(o, null, out ex)); }
private void SyncParameter(IDbCommand cmd, BaseQuery q) { }
/// <summary> /// 提交到数据库执行,成功:返回受影响的行数,如果执行不成功,返回-1 /// </summary> /// <param name="o">执行的SqlQuery:成功:返回受影响的行数,如果执行不成功,返回-1</param> /// <returns>返回受影响的行数</returns> internal static Int32 Submit(this BaseQuery o, out Exception exception) { return(GetSubmit(o, null, out exception)); }
private static IDataReader ExecuteReader(BaseQuery q, DataAccess da) { da.Open(); return(da.ExecuteReader(q)); }
/// <summary> /// 提交到数据库执行,成功:返回受影响的行数,如果执行不成功,返回-1 /// </summary> /// <param name="o">执行的SqlQuery:成功:返回受影响的行数,如果执行不成功,返回-1</param> /// <returns>返回受影响的行数</returns> public static Int32 Submit(this BaseQuery o, string targetdb, out Exception exception) { return(GetSubmit(o, targetdb, out exception)); }
public XmlDocument ExecuteXmlDoc(BaseQuery q) { throw new NotImplementedException(); }
internal static bool GetSubmit(List <BaseQuery> list, ScopeCommandInfo scopecommandInfo, out Exception Ex, List <BulkCopyModel> bulkModels, List <DataTable> bulkTablies, string targetdb) { bool bl = true; Ex = null; if ((list == null || list.Count == 0) && (bulkModels == null || bulkModels.Count == 0)) { bl = true; } else { try { var pty = dc.conn(targetdb); var index = 0; list.ForEach(p => { if (p.excutParBag == null) { string error = "错误:core-excutParBag为null.事务语句索引:请检查业务执行语句." + index.ToSafeString(); LogService.Default.Fatal(error); throw new Exception(error); } p.Convert(targetdb); index++; }); if (bulkModels != null && bulkModels.Count > 0) { bulkTablies = bulkModels.ConvertBulkTable(targetdb); } if (scopecommandInfo == null) { scopecommandInfo = default(ScopeCommandInfo); } BaseQuery q = null; if (list != null && list.Count > 0) { q = list.ConvertOneQuery(); scopecommandInfo.Parameters = q.Parameters; scopecommandInfo.SqlCommand = q.CommandText; } List <BaseQuery> ql = null; if (q != null) { ql = new List <BaseQuery>() { q }; } bl = ModelOpretion.ExecuteBacheNonQuery(ql, out Ex, bulkTablies, targetdb); } catch (Exception ex) { bl = false; Ex = ex; LogService.Default.Fatal("处理事务语句时出现异常:" + ex.Message); } } return(bl); }
public static object ExecuteScalar(BaseQuery q, DatabaseProperty dp) { DataAccess da = new DataAccess(dp.Reader.ConnectionString, dp.Reader.DatabaseType); return(DataAccess.ExecuteScalar(q, da)); }
/// <summary> /// 供新增的时候使用,新增并且取出Identity /// </summary> /// <param name="q"></param> /// <param name="dp"></param> /// <returns></returns> internal static object ExecuteScalarToWriterOnlyForInsertRentrunIdentity(BaseQuery q, DatabaseProperty dp) { DataAccess da = new DataAccess(dp.Writer.ConnectionString, dp.Writer.DatabaseType); return(DataAccess.ExecuteScalar(q, da)); }