{public class SqlStructureHelps{#region 增删改查public static string TruncateTable<T>(){try{Type type = typeof(T);var tableName = GetClassName(type);return GetSql(SqlType.TruncateTable, tableName);}catch (Exception ex){throw ex;}}public static string Update<T>(string condition = "", List<string> param = null){try{Type type = typeof(T);var tableName = GetClassName(type);var conditionStr = "";if (!string.IsNullOrEmpty(condition)){conditionStr += " WHERE " + condition;}return GetSql(SqlType.Update, tableName, param, conditionStr);}catch (Exception ex){throw ex;}}public static string Add<T>(List<string> param = null){try{Type type = typeof(T);var tableName = GetClassName(type);return GetSql(SqlType.Insert, tableName, param);}catch (Exception ex){throw ex;}}public static string Delete<T>(string condition = ""){try{Type type = typeof(T);var tableName = GetClassName(type);var conditionStr = "";if (!string.IsNullOrEmpty(condition)){conditionStr += " WHERE " + condition;}return GetSql(SqlType.Delete, tableName, null, conditionStr);}catch (Exception ex){throw ex;}}public static string Query<T>(string condition = "", int v1 = 0, int v2 = 0, List<string> param = null){try{var arrStr = new List<string>();var conditionStr = "";if (!string.IsNullOrEmpty(condition)){conditionStr += " WHERE " + condition;}if (v1 > 0 && v2 > 0){conditionStr += string.Format(@" LIMIT {1} OFFSET ({0} - 1) * {1}", v1, v2);}Type type = typeof(T);var tableName = GetClassName(type);if (param != null && param.Count() > 0){arrStr = param.ToList();}else{var columns = GetTableNames(type, param);arrStr = columns.Select(x => x.name).ToList();}return GetSql(SqlType.Select, tableName, arrStr, conditionStr);}catch (Exception ex){throw ex;}}private static string GetSql(SqlType sqlType, string table, List<string> columns = null, string condition = ""){var s = "";switch (sqlType){case SqlType.Insert:if (columns == null || columns.Count < 1){throw new Exception("新增字段为空");}s += string.Format(@"INSERT INTO {0} ({1}) VALUES ({2});", table, string.Join(",", columns), string.Join(",", columns.Select(x => "@" + x)));break;case SqlType.Delete:s += string.Format(@"DELETE FROM {0} {1};", table, condition);break;case SqlType.Update:if (columns == null || columns.Count < 1){throw new Exception("更新字段为空");}s += string.Format(@"UPDATE {0} SET {1} {2};", table, string.Join(",", columns.Select(x => x + "=@" + x)), condition);break;case SqlType.Select:if (columns == null || columns.Count < 1){s += string.Format(@"SELECT * FROM {0} {1};", table, condition);}else{s += string.Format(@"SELECT {1} FROM {0} {2};", table, string.Join(",", columns), condition);}break;case SqlType.TruncateTable:s += string.Format(@"TRUNCATE TABLE {0};", table);break;}return s;}private static string GetClassName(Type type){var name = type.Name;object[] attrClassName = type.GetCustomAttributes(typeof(MyIsStructureAttribute), true);if (attrClassName != null && attrClassName.Length > 0){var myIsStructureAttribute = (MyIsStructureAttribute)attrClassName.First();name = myIsStructureAttribute.TableName;}return name;}private static List<Column> GetTableNames(Type type, object obj = null){var list = new List<Column>();PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);if (properties.Length > 0){foreach (PropertyInfo property in properties){if (property.CanWrite && property.CanRead){var a = property.GetCustomAttributes(typeof(MyIsStructureAttribute), true);var isNext = true;if (a != null && a.Length > 0){var temp = (MyIsStructureAttribute)a.First();isNext = temp.IsStructure;}if (isNext){var tempuu = new Column();tempuu.name = property.Name;tempuu.type = property.GetMethod.ReturnType.Name;if (obj != null){tempuu.value = property.GetMethod.Invoke(obj, null);}list.Add(tempuu);}}}}else{throw new Exception("未查询到字段");}return list;}#endregion#region 扩展public static string GetTable(SqlTypes sqlTypes, string database = ""){try{string sql = "";switch (sqlTypes){case SqlTypes.Mysql:if (string.IsNullOrEmpty(database)) throw new Exception("数据库名称不能为空");sql = string.Format(@"SELECT TABLE_NAME AS `TableName`, TABLE_COMMENT AS `TableExegesis` FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{0}' ORDER BY TABLE_NAME;", database);break;case SqlTypes.SqlServer:sql = string.Format(@"SELECT t.name AS TableName, ep.value AS TableExegesis FROM sys.tables t LEFT JOIN sys.extended_properties ep ON t.object_id = ep.major_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' AND ep.class = 1 WHERE t.type = 'U' AND t.is_ms_shipped = 0 ORDER BY t.name;");break;default:throw new Exception("未扩展的数据库");}return sql;}catch (Exception ex){throw ex;}}public static string GetColumn(SqlTypes sqlTypes, string database, string tablename){try{string sql = "";switch (sqlTypes){case SqlTypes.Mysql:sql = string.Format(@"SELECT COLUMN_NAME AS `columnName`, COLUMN_COMMENT AS `columnExegesis`, DATA_TYPE AS `columnType`, CHARACTER_MAXIMUM_LENGTH AS `columnMax` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}'; ", database, tablename);break;case SqlTypes.SqlServer:sql = string.Format(@"SELECT c.name AS columnName, ty.name AS columnType, CASE WHEN ty.name IN ('nchar', 'nvarchar', 'ntext') THEN c.max_length / 2 WHEN ty.name IN ('text') THEN -1 ELSE c.max_length END AS columnMax, ep.value AS columnExegesis FROM sys.columns c INNER JOIN sys.types ty ON c.user_type_id = ty.user_type_id LEFT JOIN sys.extended_properties ep ON c.object_id = ep.major_id AND c.column_id = ep.minor_id AND ep.name = 'MS_Description' WHERE c.object_id = OBJECT_ID('{0}.dbo.{1}'); ", database, tablename);break;default:throw new Exception("未扩展的数据库");}return sql;}catch (Exception ex){throw ex;}}public static Type MySqlTypeToCSharpType(string mysqlType){switch (mysqlType.ToLowerInvariant()){case "int":case "tinyint":case "smallint":case "mediumint":case "bigint":case "bigint unsigned":case "int unsigned":return typeof(int);case "float":case "double":case "decimal":case "numeric":return typeof(double);case "varchar":case "char":case "text":case "tinytext":case "mediumtext":case "longtext":return typeof(string);case "datetime":case "timestamp":case "date":case "time":case "year":return typeof(DateTime);case "blob":case "tinyblob":case "mediumblob":case "longblob":case "binary":case "varbinary":return typeof(byte[]);case "json":return typeof(string);case "bit":return typeof(bool);default:throw new ArgumentException($"MySQL type: {mysqlType}");}}public static Type SqlServerTypeToCSharpType(string sqlType){switch (sqlType.ToLowerInvariant()){case "int":case "smallint":case "tinyint":return typeof(int);case "bigint":return typeof(long);case "bit":return typeof(bool);case "decimal":case "numeric":return typeof(decimal);case "float":return typeof(float);case "real":return typeof(float);case "money":case "smallmoney":return typeof(decimal);case "char":case "nchar":case "varchar":case "nvarchar":case "text":case "ntext":return typeof(string);case "datetime":case "smalldatetime":case "date":case "time":case "datetime2":case "datetimeoffset":return typeof(DateTime);case "binary":case "varbinary":case "varbinary(max)":return typeof(byte[]);case "uniqueidentifier":return typeof(Guid);case "sql_variant":return typeof(object);case "xml":return typeof(string);default:throw new ArgumentException($"SQL Server type: {sqlType}");}}#endregion}#region 内部辅助使用enum SqlType{Insert,Delete,Update,Select,TruncateTable}class Column{public string name { get; set; }public object value { get; set; }public string type { get; set; }}#endregion#region 外部配合使用public class MyIsStructureAttribute : Attribute{public MyIsStructureAttribute(bool isStructure = false){IsStructure = isStructure;}public MyIsStructureAttribute(string tableName){TableName = tableName;}public bool IsStructure { get; }public string TableName { get; }}public enum SqlTypes{Mysql,SqlServer}public class Tables{public string TableName { get; set; }public string TableExegesis { get; set; }}public class Columns{public string columnName { get; set; }public string columnExegesis { get; set; }public string columnType { get; set; }public string columnMax { get; set; }}#endregion}