DbHelperSQL
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace System { [System.Diagnostics.DebuggerDisplay("connectionString={connectionString}")] public abstract class DbHelperSQL { public static string connectionString = AppConfig.connString.ToString(); public DbHelperSQL() { } #region 公用方法 public static bool ColumnExists(string tableName,string columnName) { string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; object res = GetSingle(sql); if(res == null) { return false; } return Convert.ToInt32(res) > 0; } public static int GetMaxID(string FieldName,string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if(obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if(cmdresult == 0) { return false; } else { return true; } } public static bool IsSysObjects(string TableName) { string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') "; object obj = GetSingle(strsql); int cmdresult; if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if(cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql,params SqlParameter[] cmdParms) { object obj = GetSingle(strSql,cmdParms); int cmdresult; if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if(cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 public static int ExecuteSql(string SQLString) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(SQLString,connection)) { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } } } public static int ExecuteSqlByTime(string SQLString,int Times) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(SQLString,connection)) { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } } } public static int ExecuteSqlTran(List<String> SQLStringList) { using(SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for(int n = 0;n < SQLStringList.Count;n++) { string strsql = SQLStringList[n]; if(strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } public static void Addbatches(List<String> SQLStringList) { //分批执行 while(SQLStringList.Count > 0) { var tempParam = SQLStringList.Take(50).ToList(); ExecuteSqlTran(tempParam); SQLStringList.RemoveRange(0,tempParam.Count); } } public static void ExecuteSql(SQLParma parma) { ExecuteSql(parma.Sql,parma.Sp); } public static int ExecuteSql(string SQLString,string content) { using(SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString,connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content",SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } finally { cmd.Dispose(); connection.Close(); } } } public static object ExecuteSqlGet(string SQLString,string content) { using(SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString,connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content",SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } finally { cmd.Dispose(); connection.Close(); } } } public static int ExecuteSqlInsertImg(string SQLString,byte[] fs) { using(SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString,connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs",SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } finally { cmd.Dispose(); connection.Close(); } } } public static object GetSingle(string SQLString) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(SQLString,connection)) { connection.Open(); object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } } } public static object GetSingle(string SQLString,int Times) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(SQLString,connection)) { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } } } public static SqlDataReader ExecuteReader(string SQLString) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(SQLString,connection)) { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } } } public static DataSet Query(string SQLString) { using(SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString,connection); command.Fill(ds,"ds"); return ds; } } public static DataSet Query(string SQLString,int Times) { using(SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString,connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds,"ds"); return ds; } } public static DataTable ExecuteTable(string SQLString) { var ds = Query(SQLString); if(ds != null && ds.Tables.Count > 0) { return ds.Tables[0]; } else { return null; } } public static DataRow ExecuteRow(string SQLString) { var ds = Query(SQLString); if(ds != null && ds.Tables.Count > 0) { if(ds.Tables[0].Rows.Count > 0) { return ds.Tables[0].Rows[0]; } else { return null; } } else { return null; } } #endregion #region 执行带参数的SQL语句 public static int ExecuteSql(string SQLString,params SqlParameter[] cmdParms) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand()) { PrepareCommand(cmd,connection,null,SQLString,cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } } } public static void ExecuteSqlTran(Hashtable SQLStringList) { using(SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using(SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { foreach(DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd,conn,trans,cmdText,cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch(System.Data.SqlClient.SqlException ex) { Logger.LogError("DbHelperSQL ExecuteSqlTran connectionString=" + connectionString,ex); trans.Rollback(); } } } } public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using(SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using(SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; foreach(DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; foreach(SqlParameter q in cmdParms) { if(q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd,conn,trans,cmdText,cmdParms); int val = cmd.ExecuteNonQuery(); foreach(SqlParameter q in cmdParms) { if(q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } public static object GetSingle(string SQLString,params SqlParameter[] cmdParms) { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand()) { PrepareCommand(cmd,connection,null,SQLString,cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } } } public static SqlDataReader ExecuteReader(string SQLString,params SqlParameter[] cmdParms) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd,connection,null,SQLString,cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } public static DataSet Query(string SQLString,params SqlParameter[] cmdParms) { using(SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd,connection,null,SQLString,cmdParms); using(SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); da.Fill(ds,"ds"); cmd.Parameters.Clear(); return ds; } } } private static void PrepareCommand(SqlCommand cmd,SqlConnection conn,SqlTransaction trans,string cmdText,SqlParameter[] cmdParms) { if(conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if(trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text; if(cmdParms != null) { foreach(SqlParameter parameter in cmdParms) { if((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 存储过程操作 public static SqlDataReader RunProcedure(string storedProcName,IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection,storedProcName,parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } public static DataSet RunProcedure(string storedProcName,IDataParameter[] parameters,string tableName) { using(SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection,storedProcName,parameters); sqlDA.Fill(dataSet,tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName,IDataParameter[] parameters,string tableName,int Times) { using(SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection,storedProcName,parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet,tableName); connection.Close(); return dataSet; } } private static SqlCommand BuildQueryCommand(SqlConnection connection,string storedProcName,IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName,connection); command.CommandType = CommandType.StoredProcedure; foreach(SqlParameter parameter in parameters) { if(parameter != null) { if((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } #endregion #region MethodEx public static bool OpenDb(string connectionString) { try { using(SqlConnection connection = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand("select GETDATE()",connection)) { connection.Open(); object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null)) || (Object.Equals(obj,System.DBNull.Value))) { return false; } else { return true; } } } } catch(Exception ex) { return false; } } public static void SqlBulkCopyInsert(DataTable dtData) { using(SqlBulkCopy sqlRevdBulkCopy = new SqlBulkCopy(connectionString)) { sqlRevdBulkCopy.DestinationTableName = string.IsNullOrWhiteSpace(dtData.TableName) ? "tempdatatable_admin_" + DateTime.Now.ToShortDateString() : dtData.TableName; sqlRevdBulkCopy.NotifyAfter = dtData.Rows.Count; sqlRevdBulkCopy.WriteToServer(dtData); sqlRevdBulkCopy.Close(); } } public static string Exec(string sql) { string show = ""; using(SqlConnection con = new SqlConnection(connectionString)) { try { con.Open(); SqlCommand Com = new SqlCommand(sql,con); show = Com.ExecuteScalar().ToString(); } catch { show = ""; } return show.ToString(); } } public static SqlParameter[] GetSqlParameter(List<SqlParam> sqlParams) { List<SqlParameter> L_pars = new List<SqlParameter>(); foreach(var item in sqlParams) { L_pars.Add(new SqlParameter(item.ParamName,item.ParamValue)); } return L_pars.ToArray(); } public static DataTable ExecuteTable(string SQLString,params SqlParameter[] cmdParms) { var ds = Query(SQLString,cmdParms); if(ds != null && ds.Tables.Count > 0) { return ds.Tables[0]; } else { return null; } } public static T GetSingle<T>(string commandText,params SqlParameter[] parms) { object result = GetSingle(commandText,parms); if(result != null) { return (T)Convert.ChangeType(result,typeof(T)); ; } return default(T); } public static string GetFieldValue(string fieldName,string tableName,string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT " + fieldName + " FROM " + tableName + " "); if(!string.IsNullOrWhiteSpace(strWhere)) { strSql.Append(" WHERE " + strWhere); } return DbHelperSQL.GetSingle<string>(strSql.ToString()); } public static DataTable Get_PagingTable(string where,string ls_tablesql,string column,string sort,int page,int pageCount,SqlParameter[] parms) { string sql = @"select top (" + pageCount + ") * from (" + ls_tablesql + where + " ) as aaa where aaa.RowId between ((" + page + "-1)*" + pageCount + "+1) and (" + page + "*" + pageCount + ") " + "order by " + column + " " + sort + ""; return ExecuteTable(sql,parms); } public static DataTable GetListByPage(string strWhere,string orderby,int startIndex,int endIndex,string tableName,params SqlParameter[] cmdParms) { int i_inde, i_end; i_end = startIndex * endIndex; i_inde = (startIndex - 1) * endIndex + 1; StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if(!string.IsNullOrWhiteSpace(orderby)) { strSql.Append("order by T." + orderby); } else { strSql.Append("order by T.Id desc"); } strSql.Append(")AS Row, T.* from " + tableName + " T "); if(!string.IsNullOrWhiteSpace(strWhere)) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}",i_inde,i_end); return ExecuteTable(strSql.ToString(),cmdParms); } #endregion #region DataTable转换到List public static IList<T> ExecuteList<T>(string SQLString) { var ds = Query(SQLString); if(ds != null && ds.Tables.Count > 0) { return ToList<T>(ds.Tables[0]); } else { return null; } } public static DataTable ToDataTable<T>(IEnumerable<T> collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name,p.PropertyType)).ToArray()); if(collection.Count() > 0) { for(int i = 0;i < collection.Count();i++) { ArrayList tempList = new ArrayList(); foreach(PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i),null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array,true); } } return dt; } public static IList<T> ToList<T>(DataTable table) { if(table == null) { return null; } List<DataRow> rows = new List<DataRow>(); foreach(DataRow row in table.Rows) { rows.Add(row); } return ToList<T>(rows); } public static IList<T> ToList<T>(IList<DataRow> rows) { IList<T> list = null; if(rows != null) { list = new List<T>(); foreach(DataRow row in rows) { T item = ToModel<T>(row); list.Add(item); } } return list; } public static T ToModel<T>(DataRow row) { T obj = default(T); if(row != null) { obj = Activator.CreateInstance<T>(); foreach(DataColumn column in row.Table.Columns) { PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName); try { if(!prop.CanWrite) { continue; } object value = row[column.ColumnName]; if(value != DBNull.Value) { prop.SetValue(obj,value,null); } } catch(Exception ex) { Logger.LogError(column.ColumnName + "字段类型与实体类型不匹配 " + ex.Message); } } } return obj; } #endregion #region DbBackuper public Result BackupDatabase(string databaseName,string filename,bool isErase) { var result = DealFile(filename,isErase); if(result.Success) { try { string strCmd = "BACKUP DATABASE " + databaseName + " TO DISK = " + filename + ""; ExecuteSql(strCmd); } catch(Exception ex) { return new Result(ex); } return new Result(true); } return result; } /// <summary> /// 处理文件 /// </summary> /// <param name="filename">文件名</param> /// <param name="isErase">是否擦除</param> /// <returns></returns> private static Result DealFile(string filename,bool isErase) { try { if(File.Exists(filename)) { if(!isErase) { return new Result("文件已经存在!"); } else { File.Delete(filename); } } string directory = Path.GetDirectoryName(filename); string file = Path.GetFileName(filename); if(!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } return new Result(true); } catch(Exception ex) { return new Result(ex); } } #endregion #region DbScriptBuilder #endregion #region DbObject public void ExtendedProperty(bool addbyupdate,string describe,string tableName,string columnName = null) { string sql_propertyInfo = @"EXEC sys.{0} N'MS_Description',N'{1}',N'SCHEMA',N'dbo',N'TABLE',N'{2}',N'COLUMN',N'{3}'";//字段说明 string sql_propertyInfo1 = @"EXEC sys.{0} N'MS_Description',N'{1}',N'SCHEMA',N'dbo',N'TABLE',N'{2}'";//表说明 string sql = ""; if(addbyupdate) { if(columnName == null || columnName.Length == 0) { sql = string.Format(sql_propertyInfo1,"sp_updateextendedproperty",describe,tableName); } else { sql = string.Format(sql_propertyInfo,"sp_updateextendedproperty",describe,tableName,columnName); } } else { if(columnName == null || columnName.Length == 0) { sql = string.Format(sql_propertyInfo1,"sp_addextendedproperty",describe,tableName); } else { sql = string.Format(sql_propertyInfo,"sp_addextendedproperty",describe,tableName,columnName); } } ExecuteSql(sql); } public List<TableColumn> GetColumnInfoList(string tableName) { if(string.IsNullOrWhiteSpace(tableName)) return null; return Utils.GetOrAddCache(tableName,() => { string sql = @"SELECT d.name AS 表名, isnull(f.value, '') AS 表说明, a.colorder AS 字段序号, a.name AS 字段名,ISNULL(g.[value], '') AS 字段说明, CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '√' ELSE '' END AS 标识, CASE WHEN EXISTS(SELECT 1 FROM dbo.sysindexes si INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid INNER JOIN dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid INNER JOIN dbo.sysobjects so ON so.name = si.name AND so.xtype = 'PK' WHERE sc.id = a.id AND sc.colid = a.colid) THEN '√' ELSE '' END AS 主键, b.name AS 类型, a.length AS 长度, COLUMNPROPERTY(a.id, a.name, 'PRECISION')AS 精度, ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale'), 0) AS 小数位数,CASE WHEN a.isnullable = 1 THEN '√' ELSE '' END AS 允许空, ISNULL(e.text, '') AS 默认值 FROM dbo.syscolumns a LEFT OUTER JOIN dbo.systypes b ON a.xtype = b.xusertype INNER JOIN dbo.sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.status >= 0 LEFT OUTER JOIN dbo.syscomments e ON a.cdefault = e.id LEFT OUTER JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id AND g.name = 'MS_Description' LEFT OUTER JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 AND f.name = 'MS_Description' "; if(!string.IsNullOrWhiteSpace(tableName)) { sql = sql + " where d.name='" + tableName + "'"; } var list = new List<TableColumn>(); var dt = ExecuteTable(string.Format(sql)); foreach(DataRow row in dt.Rows) { var tc = new TableColumn(); tc.TableName = row["表名"].ToString(); tc.ColumnName = row["字段名"].ToString(); tc.ColumnRemark = row["字段说明"].ToString(); tc.ColumnType = row["类型"].ToString(); tc.DefaultValue = row["默认值"].ToString(); tc.MaxLength = Utils.GetObjTranNull<int>(row["长度"].ToString()); tc.ColumnOrder = Utils.GetObjTranNull<int>(row["字段序号"]); if(row["标识"].ToString().Length > 0) { tc.IsIdentity = true; } if(row["主键"].ToString() == "√") { tc.IsPrimaryKey = true; } if(row["允许空"].ToString() == "√") { tc.IsNullable = true; } list.Add(tc); } return list; }); } #endregion } }