我有这个代码
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();
}
Run Code Online (Sandbox Code Playgroud)
我需要通过读取"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"];
}
}
Run Code Online (Sandbox Code Playgroud)
//// if(row ["DATA_TYPE"] =="int")我如何通过DataType(Int)设置var x或如何通过在行["DATA_TYPE"]中找到的名称获取数据类型?? !!
解决方案是创建一个将 sql 类型映射到 .net 类型的字典:
Dictionary<string, Type> sqlToNetTypes;
Run Code Online (Sandbox Code Playgroud)
并用您可以在“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...
...
Run Code Online (Sandbox Code Playgroud)
然后在辅助方法中:
Type GetNETType(string sqlType)
{
if(sqlToNetTypes.ContainsKey(sqlType))
{
return sqlToNetTypes[sqlType];
}else
{
return typeof(object); //generic type
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
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"]);
}
}
Run Code Online (Sandbox Code Playgroud)