我有这个代码
using (SqlConnection conn = new SqlConnection(ConnectionString)) { conn.Open(); DataTable Databases = conn.GetSchema("Databases"); DataTable Tables = conn.GetSchema("Tables"); DataTable Columns = conn.GetSchema("Columns"); conn.close(); }
我需要通过读取“ DATA_TYPE”列中的字符串值来返回datattype
foreach (DataRow row in Columns.Rows) if (row["TABLE_NAME"].ToString() == tableName) { if (fName == row["COLUMN_NAME"].ToString()) { //return Datatype var x = row["DATA_TYPE"]; } }
//// if(row [“ DATA_TYPE”] ==“ int”)我如何通过DataType(Int)设置var x或如何通过在row [“ DATA_TYPE”]中找到的名称获取数据类型?
一个解决方案是创建一个将sql类型映射到.net类型的字典:
Dictionary<string, Type> sqlToNetTypes;
并使用在“ DATA_TYPE”列及其等效的.NET中可以找到的所有可能的类型填充它:
sqlToNetTypes.Add("int", typeof(int)); sqlToNetTypes.Add("varchar", typeof(sting)); sqlToNetTypes.Add("datetime", typeof(DateTime)); sqlToNetTypes.Add("bit", typeof(bool)); sqlToNetTypes.Add("numeric", typeof(float));//or double or decimal as you like... ...
然后在一个辅助方法中:
Type GetNETType(string sqlType) { if(sqlToNetTypes.ContainsKey(sqlType)) { return sqlToNetTypes[sqlType]; }else { return typeof(object); //generic type } }
并像这样使用它:
foreach (DataRow row in Columns.Rows) if (row["TABLE_NAME"].ToString() == tableName) { if (fName == row["COLUMN_NAME"].ToString()) { //return Datatype var x = GetNETType(row["DATA_TYPE"]); } }