获取使用C#中的SQL Server列的数据类型 [英] Get data type of a SQL Server column using C#
本文介绍了获取使用C#中的SQL Server列的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道我在做什么错,有人可以纠正吗?我需要从使用C#SQL Server数据库确定检索列的类型。
我说,我有这样的:
SqlConnection的CN =新的SqlConnection (SQL连接字符串);
的SqlCommand CMD =新的SqlCommand(SELECT * FROM [表名],CN);
SqlDataReader的RDR = cmd.ExecuteReader();
,而(rdr.Read())
{
的for(int c = 0;℃下rdr.VisibleFieldCount; C ++)
{
System.Type的类型= rdr.GetFieldType(C);
//所以我能做到这一点? (伪代码)
//开关(类型)
// {
//情况下字符串:
//情况下INT:
//案例日期时间:
//等。
//}
}
}
解决方案
您可以执行以下操作:
/ * ...代码。* /
类型的System.Type = rdr.GetFieldType(C);
开关(Type.GetTypeCode(类型))
{
情况下TypeCode.DateTime:
中断;
情况下TypeCode.String:
中断;
默认:打破;
}
/ * ...代码。* /
I'm not sure what exactly I'm doing wrong, can someone correct it please? I need to determine the type of a retrieved column from a SQL Server database using C#.
Say, I have this:
SqlConnection cn = new SqlConnection("Sql Connection String");
SqlCommand cmd = new SqlCommand("SELECT * FROM [TableName]", cn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
for (int c = 0; c < rdr.VisibleFieldCount; c++)
{
System.Type type = rdr.GetFieldType(c);
//So can I do this? (Pseudo-code)
//switch(type)
//{
//case string:
//case int:
//case DateTime:
//etc.
//}
}
}
解决方案
You can do the following:
/* ... code .... */
System.Type type = rdr.GetFieldType(c);
switch (Type.GetTypeCode(type))
{
case TypeCode.DateTime:
break;
case TypeCode.String:
break;
default: break;
}
/* ... code .... */
这篇关于获取使用C#中的SQL Server列的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文