//创建文件数据库,并添加50条数据。 void CreateTable() { Response.Write("文章见:http://www.cnblogs.com/cyq1162/p/3443244.html <hr />"); if (DBTool.ExistsTable(tableName)) { using (MAction action = new MAction(tableName)) { if (action.Fill("order by id desc")) { action.Delete("id<=" + action.Get <int>(0)); } } //DBTool.DropTable(tableName); } else { MDataColumn mdc = new MDataColumn(); mdc.Add("ID", SqlDbType.Int, true); mdc.Add("Name"); mdc.Add("CreateTime", SqlDbType.DateTime); DBTool.CreateTable(tableName, mdc); } MDataTable dt = new MDataTable(tableName); dt.Columns = DBTool.GetColumns(tableName); for (int i = 0; i < 60; i++) { dt.NewRow(true).Set(1, "Name_" + i).Set(2, DateTime.Now.AddSeconds(i)); } dt.AcceptChanges(AcceptOp.Insert); }
private void btnCreate_Click(object sender, EventArgs e) { mdc = new MDataColumn(); mdc.Add("ID", SqlDbType.Int, true, false, 11, true, null); mdc.Add("Name"); mdc.ToTable().Bind(dgvData); }
void CreateRow() { MDataColumn mdc = new MDataColumn(); mdc.Add("ID", SqlDbType.Int, true); mdc.Add("Name"); mdc.Add("CreateTime", SqlDbType.DateTime); row = new MDataRow(mdc); row.Set(0, 1).Set(1, "hello").Set(2, DateTime.Now); row.SetToAll(this); }
private void button2_Click(object sender, EventArgs e) { var tableName = this.textBox1.Text; MDataColumn col = new MDataColumn(); col.Add("Name", SqlDbType.NVarChar); col.Add("Age", SqlDbType.Int); var flag = DBTool.CreateTable(tableName, col); MessageBox.Show(flag + ""); }
private static void SetStruct(MDataColumn mdc, PropertyInfo pi, FieldInfo fi, int i, int count) { Type type = pi != null ? pi.PropertyType : fi.FieldType; string name = pi != null ? pi.Name : fi.Name; SqlDbType sqlType = SQL.DataType.GetSqlType(type); mdc.Add(name, sqlType); MCellStruct column = mdc[i]; LengthAttribute la = GetAttr <LengthAttribute>(pi, fi);//获取长度设置 if (la != null) { column.MaxSize = la.MaxSize; column.Scale = la.Scale; } if (column.MaxSize <= 0) { column.MaxSize = DataType.GetMaxSize(sqlType); } KeyAttribute ka = GetAttr <KeyAttribute>(pi, fi);//获取关键字判断 if (ka != null) { column.IsPrimaryKey = ka.IsPrimaryKey; column.IsAutoIncrement = ka.IsAutoIncrement; column.IsCanNull = ka.IsCanNull; } else if (i == 0) { column.IsPrimaryKey = true; column.IsCanNull = false; if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt)) { column.IsAutoIncrement = true; } } DefaultValueAttribute dva = GetAttr <DefaultValueAttribute>(pi, fi); if (dva != null && dva.DefaultValue != null) { if (column.SqlType == SqlDbType.Bit) { column.DefaultValue = (dva.DefaultValue.ToString() == "True" || dva.DefaultValue.ToString() == "1") ? 1 : 0; } else { column.DefaultValue = dva.DefaultValue; } } else if (i > count - 3 && sqlType == SqlDbType.DateTime && name.EndsWith("Time")) { column.DefaultValue = SqlValue.GetDate; } DescriptionAttribute da = GetAttr <DescriptionAttribute>(pi, fi);//看是否有字段描述属性。 if (da != null) { column.Description = da.Description; } }
public static bool CheckSysAutoCacheTable() { if (!HasAutoCacheTable && !string.IsNullOrEmpty(AppConfig.Cache.AutoCacheConn)) { string AutoCacheConn = AppConfig.Cache.AutoCacheConn; if (DBTool.TestConn(AutoCacheConn)) { HasAutoCacheTable = DBTool.Exists(KeyTableName, AutoCacheConn); //检测数据是否存在表 if (!HasAutoCacheTable) { MDataColumn mdc = new MDataColumn(); mdc.Add("CacheKey", System.Data.SqlDbType.NVarChar, false, false, 200, true, null); mdc.Add("CacheTime", System.Data.SqlDbType.BigInt, false, false, -1); HasAutoCacheTable = DBTool.CreateTable(KeyTableName, mdc, AutoCacheConn); if (!HasAutoCacheTable) //若创建失败,可能并发下其它进程创建了。 { HasAutoCacheTable = DBTool.Exists(KeyTableName, AutoCacheConn); //重新检测表是否存在。 } } } } return(HasAutoCacheTable); }
/// <summary> /// 生成表 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreate_Click(object sender, EventArgs e) { var dc = new MDataColumn(); var tableName = textTableName.Text; var text = textPrimary.Text; var cols = textCols.Text; var conn = textConn.Text; var list = JsonHelper.ToList <ColumnModel>(cols); foreach (ColumnModel t in list) { var cell = new MCellStruct(t.ColName, t.SqlType); if (text.ToLower().Equals(t.ColName.ToLower())) { cell.IsPrimaryKey = true; } cell.Description = t.Description; dc.Add(cell); } var msg = DBTool.CreateTable(tableName, dc, conn)?"生成成功":"生成失败"; MessageBox.Show(msg); }
public static MDataColumn GetColumns(string tableName, string conn) { string key = GetSchemaKey(tableName, conn); #region 缓存检测 if (_ColumnCache.ContainsKey(key)) { return(_ColumnCache[key].Clone()); } if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath)) { string fullPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath + key + ".ts"; if (System.IO.File.Exists(fullPath)) { MDataColumn columns = MDataColumn.CreateFrom(fullPath); if (columns.Count > 0) { CacheManage.LocalInstance.Set(key, columns.Clone(), 1440); return(columns); } } } #endregion string fixName; conn = CrossDB.GetConn(tableName, out fixName, conn ?? AppConfig.DB.DefaultConn); tableName = fixName; if (conn == null) { return(null); } MDataColumn mdcs = null; using (DalBase dbHelper = DalCreate.CreateDal(conn)) { DataBaseType dalType = dbHelper.DataBaseType; if (dalType == DataBaseType.Txt || dalType == DataBaseType.Xml) { #region 文本数据库处理。 if (!tableName.Contains(" ")) // || tableName.IndexOfAny(Path.GetInvalidPathChars()) == -1 { tableName = SqlFormat.NotKeyword(tableName); //处理database..tableName; tableName = Path.GetFileNameWithoutExtension(tableName); //视图表,带“.“的,会出问题 string fileName = dbHelper.Con.DataSource + tableName + (dalType == DataBaseType.Txt ? ".txt" : ".xml"); mdcs = MDataColumn.CreateFrom(fileName); mdcs.DataBaseType = dalType; mdcs.Conn = conn; } #endregion } else { #region 其它数据库 mdcs = new MDataColumn(); mdcs.Conn = conn; mdcs.TableName = tableName; mdcs.DataBaseType = dalType; tableName = SqlFormat.Keyword(tableName, dbHelper.DataBaseType);//加上关键字:引号 //如果table和helper不在同一个库 DalBase helper = dbHelper.ResetDalBase(tableName); helper.IsRecordDebugInfo = false || AppDebug.IsContainSysSql;//内部系统,不记录SQL表结构语句。 try { bool isView = tableName.Contains(" ");//是否视图。 if (!isView) { isView = CrossDB.Exists(tableName, "V", conn); } if (!isView) { TableInfo info = CrossDB.GetTableInfoByName(mdcs.TableName, conn); if (info != null) { mdcs.Description = info.Description; } } MCellStruct mStruct = null; SqlDbType sqlType = SqlDbType.NVarChar; if (isView) { string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName); mdcs = GetViewColumns(sqlText, ref helper); } else { mdcs.AddRelateionTableName(SqlFormat.NotKeyword(tableName)); switch (dalType) { case DataBaseType.MsSql: case DataBaseType.Oracle: case DataBaseType.MySql: case DataBaseType.Sybase: case DataBaseType.PostgreSQL: #region Sql string sql = string.Empty; if (dalType == DataBaseType.MsSql) { #region Mssql string dbName = null; if (!helper.Version.StartsWith("08")) { //先获取同义词,检测是否跨库 string realTableName = Convert.ToString(helper.ExeScalar(string.Format(MSSQL_SynonymsName, SqlFormat.NotKeyword(tableName)), false)); if (!string.IsNullOrEmpty(realTableName)) { string[] items = realTableName.Split('.'); tableName = realTableName; if (items.Length > 0) //跨库了 { dbName = realTableName.Split('.')[0]; } } } sql = GetMSSQLColumns(helper.Version.StartsWith("08"), dbName ?? helper.DataBaseName); #endregion } else if (dalType == DataBaseType.MySql) { sql = GetMySqlColumns(helper.DataBaseName); } else if (dalType == DataBaseType.Oracle) { tableName = tableName.ToUpper(); //Oracle转大写。 //先获取同义词,不检测是否跨库 string realTableName = Convert.ToString(helper.ExeScalar(string.Format(Oracle_SynonymsName, SqlFormat.NotKeyword(tableName)), false)); if (!string.IsNullOrEmpty(realTableName)) { tableName = realTableName; } sql = GetOracleColumns(); } else if (dalType == DataBaseType.Sybase) { tableName = SqlFormat.NotKeyword(tableName); sql = GetSybaseColumns(); } else if (dalType == DataBaseType.PostgreSQL) { sql = GetPostgreColumns(); } helper.AddParameters("TableName", SqlFormat.NotKeyword(tableName), DbType.String, 150, ParameterDirection.Input); DbDataReader sdr = helper.ExeDataReader(sql, false); if (sdr != null) { long maxLength; bool isAutoIncrement = false; short scale = 0; string sqlTypeName = string.Empty; while (sdr.Read()) { short.TryParse(Convert.ToString(sdr["Scale"]), out scale); if (!long.TryParse(Convert.ToString(sdr["MaxSize"]), out maxLength)) //mysql的长度可能大于int.MaxValue { maxLength = -1; } else if (maxLength > int.MaxValue) { maxLength = int.MaxValue; } sqlTypeName = Convert.ToString(sdr["SqlType"]); sqlType = DataType.GetSqlType(sqlTypeName); isAutoIncrement = Convert.ToBoolean(sdr["IsAutoIncrement"]); mStruct = new MCellStruct(mdcs.DataBaseType); mStruct.ColumnName = Convert.ToString(sdr["ColumnName"]).Trim(); mStruct.OldName = mStruct.ColumnName; mStruct.SqlType = sqlType; mStruct.IsAutoIncrement = isAutoIncrement; mStruct.IsCanNull = Convert.ToBoolean(sdr["IsNullable"]); mStruct.MaxSize = (int)maxLength; mStruct.Scale = scale; mStruct.Description = Convert.ToString(sdr["Description"]); mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, sdr["DefaultValue"], 0, sqlType); mStruct.IsPrimaryKey = Convert.ToString(sdr["IsPrimaryKey"]) == "1"; switch (dalType) { case DataBaseType.MsSql: case DataBaseType.MySql: case DataBaseType.Oracle: mStruct.IsUniqueKey = Convert.ToString(sdr["IsUniqueKey"]) == "1"; mStruct.IsForeignKey = Convert.ToString(sdr["IsForeignKey"]) == "1"; mStruct.FKTableName = Convert.ToString(sdr["FKTableName"]); break; } mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); mdcs.Add(mStruct); } sdr.Close(); if (dalType == DataBaseType.Oracle && mdcs.Count > 0) //默认没有自增概念,只能根据情况判断。 { MCellStruct firstColumn = mdcs[0]; if (firstColumn.IsPrimaryKey && firstColumn.ColumnName.ToLower().Contains("id") && firstColumn.Scale == 0 && DataType.GetGroup(firstColumn.SqlType) == 1 && mdcs.JointPrimary.Count == 1) { firstColumn.IsAutoIncrement = true; } } } #endregion break; case DataBaseType.SQLite: #region SQlite if (helper.Con.State != ConnectionState.Open) { helper.Con.Open(); } DataTable sqliteDt = helper.Con.GetSchema("Columns", new string[] { null, null, SqlFormat.NotKeyword(tableName) }); if (!helper.IsOpenTrans) { helper.Con.Close(); } int size; short sizeScale; string dataTypeName = string.Empty; foreach (DataRow row in sqliteDt.Rows) { object len = row["NUMERIC_PRECISION"]; if (len == null || len == DBNull.Value) { len = row["CHARACTER_MAXIMUM_LENGTH"]; } short.TryParse(Convert.ToString(row["NUMERIC_SCALE"]), out sizeScale); if (!int.TryParse(Convert.ToString(len), out size)) //mysql的长度可能大于int.MaxValue { size = -1; } dataTypeName = Convert.ToString(row["DATA_TYPE"]); if (dataTypeName == "text" && size > 0) { sqlType = DataType.GetSqlType("varchar"); } else { sqlType = DataType.GetSqlType(dataTypeName); } //COLUMN_NAME,DATA_TYPE,PRIMARY_KEY,IS_NULLABLE,CHARACTER_MAXIMUM_LENGTH AUTOINCREMENT mStruct = new MCellStruct(row["COLUMN_NAME"].ToString(), sqlType, Convert.ToBoolean(row["AUTOINCREMENT"]), Convert.ToBoolean(row["IS_NULLABLE"]), size); mStruct.Scale = sizeScale; mStruct.Description = Convert.ToString(row["DESCRIPTION"]); mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, row["COLUMN_DEFAULT"], 0, sqlType); //"COLUMN_DEFAULT" mStruct.IsPrimaryKey = Convert.ToBoolean(row["PRIMARY_KEY"]); mStruct.SqlTypeName = dataTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); mdcs.Add(mStruct); } #endregion break; case DataBaseType.Access: #region Access DataTable keyDt, valueDt; string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName); OleDbConnection con = new OleDbConnection(helper.Con.ConnectionString); OleDbCommand com = new OleDbCommand(sqlText, con); con.Open(); keyDt = com.ExecuteReader(CommandBehavior.KeyInfo).GetSchemaTable(); valueDt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SqlFormat.NotKeyword(tableName) }); con.Close(); con.Dispose(); if (keyDt != null && valueDt != null) { string columnName = string.Empty, sqlTypeName = string.Empty; bool isKey = false, isCanNull = true, isAutoIncrement = false; int maxSize = -1; short maxSizeScale = 0; SqlDbType sqlDbType; foreach (DataRow row in keyDt.Rows) { columnName = row["ColumnName"].ToString(); isKey = Convert.ToBoolean(row["IsKey"]); //IsKey isCanNull = Convert.ToBoolean(row["AllowDBNull"]); //AllowDBNull isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]); sqlTypeName = Convert.ToString(row["DataType"]); sqlDbType = DataType.GetSqlType(sqlTypeName); short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale); if (Convert.ToInt32(row["NumericPrecision"]) > 0) //NumericPrecision { maxSize = Convert.ToInt32(row["NumericPrecision"]); } else { long len = Convert.ToInt64(row["ColumnSize"]); if (len > int.MaxValue) { maxSize = int.MaxValue; } else { maxSize = (int)len; } } mStruct = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize); mStruct.Scale = maxSizeScale; mStruct.IsPrimaryKey = isKey; mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); foreach (DataRow item in valueDt.Rows) { if (columnName == item[3].ToString()) //COLUMN_NAME { if (item[8].ToString() != "") { mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, item[8], 0, sqlDbType); //"COLUMN_DEFAULT" } break; } } mdcs.Add(mStruct); } } #endregion break; } } } catch (Exception err) { Log.Write(err, LogType.DataBase); //helper.DebugInfo.Append(err.Message); } #endregion } } if (mdcs.Count > 0) { //移除被标志的列: string[] fields = AppConfig.DB.HiddenFields.Split(','); foreach (string item in fields) { string field = item.Trim(); if (!string.IsNullOrEmpty(field) & mdcs.Contains(field)) { mdcs.Remove(field); } } } #region 缓存设置 if (!_ColumnCache.ContainsKey(key) && mdcs.Count > 0) { _ColumnCache.Add(key, mdcs.Clone()); if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath)) { string folderPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath; if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); } mdcs.WriteSchema(folderPath + key + ".ts"); } } #endregion return(mdcs); }
static void Start() { bool result = DBTool.TestConn(AppConfig.DB.DefaultConn);//检测数据库链接是否正常 OutMsg("数据库链接:" + result); OutMsg("-----------------------------------------"); string databaseName; Dictionary <string, string> tables = DBTool.GetTables(AppConfig.DB.DefaultConn, out databaseName);//读取所有表 if (tables != null) { OutMsg("数据库:" + databaseName); foreach (KeyValuePair <string, string> item in tables) { OutMsg("表:" + item.Key + " 说明:" + item.Value); MDataColumn mdc = DBTool.GetColumns(item.Key);//读取所有列 foreach (MCellStruct ms in mdc) { OutMsg(" 列:" + ms.ColumnName + " SqlType:" + ms.SqlType); } } } OutMsg("-----------------------------------------"); string newTableName = "A18";// +DateTime.Now.Second; DalType dalType; result = DBTool.ExistsTable(newTableName, AppConfig.DB.DefaultConn, out dalType);//检测表是否存在 OutMsg("表 " + newTableName + (result ? "存在" : "不存在") + " 数据库类型:" + dalType); OutMsg("-----------------------------------------"); if (result) { result = DBTool.DropTable(newTableName); OutMsg("表 " + newTableName + " 删除?" + result); OutMsg("-----------------------------------------"); } MDataColumn newMdc = new MDataColumn(); newMdc.Add("ID", System.Data.SqlDbType.Int); newMdc.Add("Name", System.Data.SqlDbType.NVarChar); result = DBTool.CreateTable(newTableName, newMdc); OutMsg("表 " + newTableName + " 创建?" + result); OutMsg("-----------------------------------------"); newMdc[1].ColumnName = "UserName"; newMdc[1].AlterOp = AlterOp.Rename; //将新创建的表name => username newMdc.Add("Password"); newMdc[2].AlterOp = AlterOp.AddOrModify; // 新增列 Password result = DBTool.AlterTable(newTableName, newMdc); OutMsg("表 " + newTableName + " 修改结构?" + result); OutMsg("-----------------------------------------"); OutMsg("------------------其它操作-------------------"); dalType = DBTool.GetDalType("txt path={0}"); OutMsg("数据库类型为: " + dalType); OutMsg("-----------------------------------------"); OutMsg(DBTool.Keyword("表关键字", DalType.MsSql));//DBTool.NotKeyword 则取消 OutMsg(DBTool.Keyword("表关键字", DalType.Oracle)); OutMsg(DBTool.Keyword("表关键字", DalType.MySql)); OutMsg(DBTool.Keyword("表关键字", DalType.SQLite)); string changeDataType = DBTool.GetDataType(newMdc[0], DalType.Access, string.Empty); OutMsg("数据类型为: " + changeDataType); OutMsg("-----------------------------------------"); string formatValue = DBTool.FormatDefaultValue(DalType.Access, "[#GETDATE]", 1, System.Data.SqlDbType.DateTime); OutMsg("Access的日期数据类型为: " + formatValue); OutMsg("-----------------------------------------"); }
internal static MDataColumn GetColumns(DataTable tableSchema) { MDataColumn mdcs = new MDataColumn(); if (tableSchema != null && tableSchema.Rows.Count > 0) { mdcs.isViewOwner = true; string columnName = string.Empty, sqlTypeName = string.Empty, tableName = string.Empty; bool isKey = false, isCanNull = true, isAutoIncrement = false; int maxSize = -1; short maxSizeScale = 0; SqlDbType sqlDbType; string dataTypeName = "DataTypeName"; if (!tableSchema.Columns.Contains(dataTypeName)) { dataTypeName = "DataType"; } bool isHasAutoIncrement = tableSchema.Columns.Contains("IsAutoIncrement"); bool isHasHidden = tableSchema.Columns.Contains("IsHidden"); string hiddenFields = "," + AppConfig.DB.HiddenFields.ToLower() + ","; for (int i = 0; i < tableSchema.Rows.Count; i++) { DataRow row = tableSchema.Rows[i]; tableName = Convert.ToString(row["BaseTableName"]); mdcs.AddRelateionTableName(tableName); if (isHasHidden && Convert.ToString(row["IsHidden"]) == "True")// !dcList.Contains(columnName)) { continue;//�����Ǹ����������ֶΡ� } columnName = row["ColumnName"].ToString(); if (string.IsNullOrEmpty(columnName)) { columnName = "Empty_" + i; } #region �����Ƿ������� bool isHiddenField = hiddenFields.IndexOf("," + columnName + ",", StringComparison.OrdinalIgnoreCase) > -1; if (isHiddenField) { continue; } #endregion bool.TryParse(Convert.ToString(row["IsKey"]), out isKey); bool.TryParse(Convert.ToString(row["AllowDBNull"]), out isCanNull); // isKey = Convert.ToBoolean();//IsKey //isCanNull = Convert.ToBoolean(row["AllowDBNull"]);//AllowDBNull if (isHasAutoIncrement) { isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]); } sqlTypeName = Convert.ToString(row[dataTypeName]); sqlDbType = DataType.GetSqlType(sqlTypeName); if (short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale) && maxSizeScale == 255) { maxSizeScale = 0; } if (!int.TryParse(Convert.ToString(row["NumericPrecision"]), out maxSize) || maxSize == 255)//NumericPrecision { long len; if (long.TryParse(Convert.ToString(row["ColumnSize"]), out len)) { if (len > int.MaxValue) { maxSize = int.MaxValue; } else { maxSize = (int)len; } } } MCellStruct mStruct = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize); mStruct.Scale = maxSizeScale; mStruct.IsPrimaryKey = isKey; mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = tableName; mStruct.OldName = mStruct.ColumnName; mStruct.ReaderIndex = i; mdcs.Add(mStruct); } tableSchema = null; } return mdcs; }
public static MDataColumn GetColumns(string tableName, ref DbBase dbHelper) { tableName = Convert.ToString(SqlCreate.SqlToViewSql(tableName)); DalType dalType = dbHelper.dalType; tableName = SqlFormat.Keyword(tableName, dbHelper.dalType); string key = GetSchemaKey(tableName, dbHelper.DataBase, dbHelper.dalType); if (CacheManage.LocalInstance.Contains(key))//�������ȡ { return CacheManage.LocalInstance.Get<MDataColumn>(key).Clone(); } switch (dalType) { case DalType.SQLite: case DalType.MySql: tableName = SqlFormat.NotKeyword(tableName); break; case DalType.Txt: case DalType.Xml: tableName = Path.GetFileNameWithoutExtension(tableName);//��ͼ�������.���ģ�������� string fileName = dbHelper.Con.DataSource + tableName + (dalType == DalType.Txt ? ".txt" : ".xml"); return MDataColumn.CreateFrom(fileName); } MDataColumn mdcs = new MDataColumn(); mdcs.dalType = dbHelper.dalType; //���table��helper����ͬһ���� DbBase helper = dbHelper.ResetDbBase(tableName); helper.IsAllowRecordSql = false;//�ڲ�ϵͳ������¼SQL��ṹ��䡣 try { bool isView = tableName.Contains(" ");//�Ƿ���ͼ�� if (!isView) { isView = Exists("V", tableName, ref helper); } MCellStruct mStruct = null; SqlDbType sqlType = SqlDbType.NVarChar; if (isView) { string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName); mdcs = GetViewColumns(sqlText, ref helper); } else { mdcs.AddRelateionTableName(SqlFormat.NotKeyword(tableName)); switch (dalType) { case DalType.MsSql: case DalType.Oracle: case DalType.MySql: case DalType.Sybase: #region Sql string sql = string.Empty; if (dalType == DalType.MsSql) { string dbName = null; if (!helper.Version.StartsWith("08")) { //�Ȼ�ȡͬ��ʣ�����Ƿ��� string realTableName = Convert.ToString(helper.ExeScalar(string.Format(SynonymsName, SqlFormat.NotKeyword(tableName)), false)); if (!string.IsNullOrEmpty(realTableName)) { string[] items = realTableName.Split('.'); tableName = realTableName; if (items.Length > 0)//����� { dbName = realTableName.Split('.')[0]; } } } sql = GetMSSQLColumns(helper.Version.StartsWith("08"), dbName ?? helper.DataBase); } else if (dalType == DalType.MySql) { sql = GetMySqlColumns(helper.DataBase); } else if (dalType == DalType.Oracle) { sql = GetOracleColumns(); } else if (dalType == DalType.Sybase) { tableName = SqlFormat.NotKeyword(tableName); sql = GetSybaseColumns(); } helper.AddParameters("TableName", tableName, DbType.String, 150, ParameterDirection.Input); DbDataReader sdr = helper.ExeDataReader(sql, false); if (sdr != null) { long maxLength; bool isAutoIncrement = false; short scale = 0; string sqlTypeName = string.Empty; while (sdr.Read()) { short.TryParse(Convert.ToString(sdr["Scale"]), out scale); if (!long.TryParse(Convert.ToString(sdr["MaxSize"]), out maxLength))//mysql�ij��ȿ��ܴ���int.MaxValue { maxLength = -1; } else if (maxLength > int.MaxValue) { maxLength = int.MaxValue; } sqlTypeName = Convert.ToString(sdr["SqlType"]); sqlType = DataType.GetSqlType(sqlTypeName); isAutoIncrement = Convert.ToBoolean(sdr["IsAutoIncrement"]); mStruct = new MCellStruct(mdcs.dalType); mStruct.ColumnName = Convert.ToString(sdr["ColumnName"]).Trim(); mStruct.OldName = mStruct.ColumnName; mStruct.SqlType = sqlType; mStruct.IsAutoIncrement = isAutoIncrement; mStruct.IsCanNull = Convert.ToBoolean(sdr["IsNullable"]); mStruct.MaxSize = (int)maxLength; mStruct.Scale = scale; mStruct.Description = Convert.ToString(sdr["Description"]); mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, sdr["DefaultValue"], 0, sqlType); mStruct.IsPrimaryKey = Convert.ToString(sdr["IsPrimaryKey"]) == "1"; switch (dalType) { case DalType.MsSql: case DalType.MySql: case DalType.Oracle: mStruct.IsUniqueKey = Convert.ToString(sdr["IsUniqueKey"]) == "1"; mStruct.IsForeignKey = Convert.ToString(sdr["IsForeignKey"]) == "1"; mStruct.FKTableName = Convert.ToString(sdr["FKTableName"]); break; } mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); mdcs.Add(mStruct); } sdr.Close(); if (dalType == DalType.Oracle && mdcs.Count > 0)//Ĭ��û���������ֻ�ܸ�������жϡ� { MCellStruct firstColumn = mdcs[0]; if (firstColumn.IsPrimaryKey && firstColumn.ColumnName.ToLower().Contains("id") && firstColumn.Scale == 0 && DataType.GetGroup(firstColumn.SqlType) == 1 && mdcs.JointPrimary.Count == 1) { firstColumn.IsAutoIncrement = true; } } } #endregion break; case DalType.SQLite: #region SQlite if (helper.Con.State != ConnectionState.Open) { helper.Con.Open(); } DataTable sqliteDt = helper.Con.GetSchema("Columns", new string[] { null, null, tableName }); if (!helper.isOpenTrans) { helper.Con.Close(); } int size; short sizeScale; string dataTypeName = string.Empty; foreach (DataRow row in sqliteDt.Rows) { object len = row["NUMERIC_PRECISION"]; if (len == null) { len = row["CHARACTER_MAXIMUM_LENGTH"]; } short.TryParse(Convert.ToString(row["NUMERIC_SCALE"]), out sizeScale); if (!int.TryParse(Convert.ToString(len), out size))//mysql�ij��ȿ��ܴ���int.MaxValue { size = -1; } dataTypeName = Convert.ToString(row["DATA_TYPE"]); if (dataTypeName == "text" && size > 0) { sqlType = DataType.GetSqlType("varchar"); } else { sqlType = DataType.GetSqlType(dataTypeName); } //COLUMN_NAME,DATA_TYPE,PRIMARY_KEY,IS_NULLABLE,CHARACTER_MAXIMUM_LENGTH AUTOINCREMENT mStruct = new MCellStruct(row["COLUMN_NAME"].ToString(), sqlType, Convert.ToBoolean(row["AUTOINCREMENT"]), Convert.ToBoolean(row["IS_NULLABLE"]), size); mStruct.Scale = sizeScale; mStruct.Description = Convert.ToString(row["DESCRIPTION"]); mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, row["COLUMN_DEFAULT"], 0, sqlType);//"COLUMN_DEFAULT" mStruct.IsPrimaryKey = Convert.ToBoolean(row["PRIMARY_KEY"]); mStruct.SqlTypeName = dataTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); mdcs.Add(mStruct); } #endregion break; case DalType.Access: #region Access DataTable keyDt, valueDt; string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName); OleDbConnection con = new OleDbConnection(helper.Con.ConnectionString); OleDbCommand com = new OleDbCommand(sqlText, con); con.Open(); keyDt = com.ExecuteReader(CommandBehavior.KeyInfo).GetSchemaTable(); valueDt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SqlFormat.NotKeyword(tableName) }); con.Close(); con.Dispose(); if (keyDt != null && valueDt != null) { string columnName = string.Empty, sqlTypeName = string.Empty; bool isKey = false, isCanNull = true, isAutoIncrement = false; int maxSize = -1; short maxSizeScale = 0; SqlDbType sqlDbType; foreach (DataRow row in keyDt.Rows) { columnName = row["ColumnName"].ToString(); isKey = Convert.ToBoolean(row["IsKey"]);//IsKey isCanNull = Convert.ToBoolean(row["AllowDBNull"]);//AllowDBNull isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]); sqlTypeName = Convert.ToString(row["DataType"]); sqlDbType = DataType.GetSqlType(sqlTypeName); short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale); if (Convert.ToInt32(row["NumericPrecision"]) > 0)//NumericPrecision { maxSize = Convert.ToInt32(row["NumericPrecision"]); } else { long len = Convert.ToInt64(row["ColumnSize"]); if (len > int.MaxValue) { maxSize = int.MaxValue; } else { maxSize = (int)len; } } mStruct = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize); mStruct.Scale = maxSizeScale; mStruct.IsPrimaryKey = isKey; mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = SqlFormat.NotKeyword(tableName); foreach (DataRow item in valueDt.Rows) { if (columnName == item[3].ToString())//COLUMN_NAME { if (item[8].ToString() != "") { mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, item[8], 0, sqlDbType);//"COLUMN_DEFAULT" } break; } } mdcs.Add(mStruct); } } #endregion break; } } helper.ClearParameters(); } catch (Exception err) { helper.debugInfo.Append(err.Message); } finally { helper.IsAllowRecordSql = true;//�ָ���¼SQL��ṹ��䡣 if (helper != dbHelper) { helper.Dispose(); } } if (mdcs.Count > 0) { //�Ƴ�����־���У� string[] fields = AppConfig.DB.HiddenFields.Split(','); foreach (string item in fields) { string field = item.Trim(); if (!string.IsNullOrEmpty(field) & mdcs.Contains(field)) { mdcs.Remove(field); } } } if (!CacheManage.LocalInstance.Contains(key)) { CacheManage.LocalInstance.Add(key, mdcs.Clone()); } return mdcs; }
public static MDataColumn GetColumns(Type typeInfo) { string key = "ColumnCache:" + typeInfo.FullName; if (columnCache.ContainsKey(key)) { return columnCache[key].Clone(); } else { #region ��ȡ�нṹ MDataColumn mdc = new MDataColumn(); switch (StaticTool.GetSystemType(ref typeInfo)) { case SysType.Base: case SysType.Enum: mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false); return mdc; case SysType.Generic: case SysType.Collection: Type[] argTypes; Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes); foreach (Type type in argTypes) { mdc.Add(type.Name, DataType.GetSqlType(type), false); } argTypes = null; return mdc; } PropertyInfo[] pis = StaticTool.GetPropertyInfo(typeInfo); SqlDbType sqlType; for (int i = 0; i < pis.Length; i++) { sqlType = SQL.DataType.GetSqlType(pis[i].PropertyType); mdc.Add(pis[i].Name, sqlType); MCellStruct column = mdc[i]; column.MaxSize = DataType.GetMaxSize(sqlType); if (i == 0) { column.IsPrimaryKey = true; column.IsCanNull = false; if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt)) { column.IsAutoIncrement = true; } } else if (i > pis.Length - 3 && sqlType == SqlDbType.DateTime && pis[i].Name.EndsWith("Time")) { column.DefaultValue = SqlValue.GetDate; } } pis = null; #endregion if (!columnCache.ContainsKey(key)) { columnCache.Add(typeInfo.FullName, mdc.Clone()); } return mdc; } }
internal static MDataColumn GetColumns(DataTable tableSchema) { MDataColumn mdcs = new MDataColumn(); if (tableSchema != null && tableSchema.Rows.Count > 0) { mdcs.isViewOwner = true; string columnName = string.Empty, sqlTypeName = string.Empty, tableName = string.Empty; bool isKey = false, isCanNull = true, isAutoIncrement = false; int maxSize = -1; short maxSizeScale = 0; SqlDbType sqlDbType; string dataTypeName = "DataTypeString"; if (!tableSchema.Columns.Contains(dataTypeName)) { dataTypeName = "DataType"; if (!tableSchema.Columns.Contains(dataTypeName)) { dataTypeName = "DataTypeName"; } } bool isHasAutoIncrement = tableSchema.Columns.Contains("IsAutoIncrement"); bool isHasHidden = tableSchema.Columns.Contains("IsHidden"); string hiddenFields = "," + AppConfig.DB.HiddenFields.ToLower() + ","; for (int i = 0; i < tableSchema.Rows.Count; i++) { DataRow row = tableSchema.Rows[i]; tableName = Convert.ToString(row["BaseTableName"]); mdcs.AddRelateionTableName(tableName); if (isHasHidden && Convert.ToString(row["IsHidden"]) == "True") // !dcList.Contains(columnName)) { continue; //后面那个会多出关联字段。 } columnName = row["ColumnName"].ToString(); if (string.IsNullOrEmpty(columnName)) { columnName = "Empty_" + i; } #region 处理是否隐藏列 bool isHiddenField = hiddenFields.IndexOf("," + columnName + ",", StringComparison.OrdinalIgnoreCase) > -1; if (isHiddenField) { continue; } #endregion bool.TryParse(Convert.ToString(row["IsKey"]), out isKey); bool.TryParse(Convert.ToString(row["AllowDBNull"]), out isCanNull); // isKey = Convert.ToBoolean();//IsKey //isCanNull = Convert.ToBoolean(row["AllowDBNull"]);//AllowDBNull if (isHasAutoIncrement) { isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]); } sqlTypeName = Convert.ToString(row[dataTypeName]); sqlDbType = DataType.GetSqlType(sqlTypeName); if (short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale) && maxSizeScale == 255) { maxSizeScale = 0; } if (!int.TryParse(Convert.ToString(row["NumericPrecision"]), out maxSize) || maxSize == 255)//NumericPrecision { long len; if (long.TryParse(Convert.ToString(row["ColumnSize"]), out len)) { if (len > int.MaxValue) { maxSize = int.MaxValue; } else { maxSize = (int)len; } } } MCellStruct mStruct = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize); mStruct.Scale = maxSizeScale; mStruct.IsPrimaryKey = isKey; mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = tableName; mStruct.OldName = mStruct.ColumnName; mStruct.ReaderIndex = i; mdcs.Add(mStruct); } tableSchema = null; } return(mdcs); }
public static MDataColumn GetColumns(Type typeInfo) { string key = "ColumnCache:" + typeInfo.FullName; if (columnCache.ContainsKey(key)) { return(columnCache[key].Clone()); } else { #region 获取列结构 MDataColumn mdc = new MDataColumn(); switch (StaticTool.GetSystemType(ref typeInfo)) { case SysType.Base: case SysType.Enum: mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false); return(mdc); case SysType.Generic: case SysType.Collection: Type[] argTypes; Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes); foreach (Type type in argTypes) { mdc.Add(type.Name, DataType.GetSqlType(type), false); } argTypes = null; return(mdc); } PropertyInfo[] pis = StaticTool.GetPropertyInfo(typeInfo); SqlDbType sqlType; for (int i = 0; i < pis.Length; i++) { sqlType = SQL.DataType.GetSqlType(pis[i].PropertyType); mdc.Add(pis[i].Name, sqlType); MCellStruct column = mdc[i]; column.MaxSize = DataType.GetMaxSize(sqlType); if (i == 0) { column.IsPrimaryKey = true; column.IsCanNull = false; if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt)) { column.IsAutoIncrement = true; } } else if (i > pis.Length - 3 && sqlType == SqlDbType.DateTime && pis[i].Name.EndsWith("Time")) { column.DefaultValue = SqlValue.GetDate; } } pis = null; #endregion if (!columnCache.ContainsKey(key)) { columnCache.Add(typeInfo.FullName, mdc.Clone()); } return(mdc); } }
private static void GetViewColumns(string sqlText, MDataColumn mdcs, ref DbBase helper) { helper.OpenCon(null); helper.Com.CommandText = sqlText; DbDataReader sdr = helper.Com.ExecuteReader(CommandBehavior.KeyInfo); DataTable keyDt = null; if (sdr != null) { keyDt = sdr.GetSchemaTable(); sdr.Close(); } //helper.CloseCon(); if (keyDt != null && keyDt.Rows.Count > 0) { mdcs.isViewOwner = true; //DataColumnCollection dcList = helper.ExeDataTable(sqlText, false).Columns; string columnName = string.Empty, sqlTypeName = string.Empty, tableName = string.Empty; bool isKey = false, isCanNull = true, isAutoIncrement = false; int maxSize = -1; short maxSizeScale = 0; SqlDbType sqlDbType; string dataTypeName = "DataTypeName"; if (!keyDt.Columns.Contains(dataTypeName)) { dataTypeName = "DataType"; } bool isHasAutoIncrement = keyDt.Columns.Contains("IsAutoIncrement"); bool isHasHidden = keyDt.Columns.Contains("IsHidden"); foreach (DataRow row in keyDt.Rows) { if (isHasHidden && Convert.ToString(row["IsHidden"]) == "True")// !dcList.Contains(columnName)) { continue;//�����Ǹ����������ֶΡ� } columnName = row["ColumnName"].ToString(); isKey = Convert.ToBoolean(row["IsKey"]);//IsKey isCanNull = Convert.ToBoolean(row["AllowDBNull"]);//AllowDBNull if (isHasAutoIncrement) { isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]); } sqlTypeName = Convert.ToString(row[dataTypeName]); sqlDbType = DataType.GetSqlType(sqlTypeName); tableName = Convert.ToString(row["BaseTableName"]); if (short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale) && maxSizeScale == 255) { maxSizeScale = 0; } if (!int.TryParse(Convert.ToString(row["NumericPrecision"]), out maxSize) || maxSize == 255)//NumericPrecision { long len; if (long.TryParse(Convert.ToString(row["ColumnSize"]), out len)) { if (len > int.MaxValue) { maxSize = int.MaxValue; } else { maxSize = (int)len; } } } MCellStruct mStruct = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize); mStruct.Scale = maxSizeScale; mStruct.IsPrimaryKey = isKey; mStruct.SqlTypeName = sqlTypeName; mStruct.TableName = tableName; mStruct.OldName = mStruct.ColumnName; mdcs.Add(mStruct); } keyDt = null; } }
public static MDataColumn GetColumns(Type typeInfo) { string key = "ColumnCache_" + typeInfo.FullName; if (_ColumnCache.ContainsKey(key)) { return(_ColumnCache[key].Clone()); } else { #region 获取列结构 MDataColumn mdc = new MDataColumn(); mdc.TableName = typeInfo.Name; switch (StaticTool.GetSystemType(ref typeInfo)) { case SysType.Base: case SysType.Enum: mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false); return(mdc); case SysType.Generic: case SysType.Collection: Type[] argTypes; Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes); foreach (Type type in argTypes) { mdc.Add(type.Name, DataType.GetSqlType(type), false); } argTypes = null; return(mdc); } List <PropertyInfo> pis = StaticTool.GetPropertyInfo(typeInfo); if (pis.Count > 0) { for (int i = 0; i < pis.Count; i++) { SetStruct(mdc, pis[i], null, i, pis.Count); } } else { List <FieldInfo> fis = StaticTool.GetFieldInfo(typeInfo); if (fis.Count > 0) { for (int i = 0; i < fis.Count; i++) { SetStruct(mdc, null, fis[i], i, fis.Count); } } } object[] tableAttr = typeInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);//看是否设置了表特性,获取表名和表描述 if (tableAttr != null && tableAttr.Length == 1) { DescriptionAttribute attr = tableAttr[0] as DescriptionAttribute; if (attr != null && !string.IsNullOrEmpty(attr.Description)) { mdc.Description = attr.Description; } } pis = null; #endregion if (!_ColumnCache.ContainsKey(key)) { _ColumnCache.Set(key, mdc.Clone()); } return(mdc); } }