如何获取DataTable中某一列的SqlType?

发布于 2024-12-05 02:35:56 字数 643 浏览 0 评论 0原文

我有一个从 SQL 数据库获取的 DataTable,如下所示:

using (SqlCommand cmd = new SqlCommand(query, _sqlserverDB))
{
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    {
        DataSet dataSet = new DataSet();
        adapter.Fill(dataSet);
        result = (dataSet != null && dataSet.Tables != null && dataSet.Tables.Count > 0) ? dataSet.Tables[0] : null;
    }
}

当我尝试通过 dataColumn.DataType 获取每列的 DataType 时,我得到了 C# 类型(Int32、Int64、String 等)。

问题:如何访问本机 SQL 数据类型(varchar、nvarchar、bigint...)而不是 C# 类型?

我尝试过 dataColumn.DataType.UnderlyingSystemType ,结果是相同的。

I have a DataTable obtained from a SQL DataBase, like this:

using (SqlCommand cmd = new SqlCommand(query, _sqlserverDB))
{
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    {
        DataSet dataSet = new DataSet();
        adapter.Fill(dataSet);
        result = (dataSet != null && dataSet.Tables != null && dataSet.Tables.Count > 0) ? dataSet.Tables[0] : null;
    }
}

When I try to get the DataType of each column through dataColumn.DataType , I get the C# types (Int32, Int64, String, etc).

QUESTION: How can I access the native SQL data types (varchar, nvarchar, bigint...) instead of the C# types?

I have tried dataColumn.DataType.UnderlyingSystemType and the result is the same.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

总以为 2024-12-12 02:35:56

当然,可以采用列的 SqlDbType,答案就在这里: 链接

SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF";
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];

Of course it is possible to take SqlDbType of a column, the answer is here on SO: link.

SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF";
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];
极度宠爱 2024-12-12 02:35:56

不能,因为 System.Data.DataTable(或 DataColumnDataSetDataRow...)通用 .NET 数据容器,无论您加载数据的特定数据库引擎如何,它都以相同的方式工作。

这意味着,如果您使用适用于 SQL Server、MySQL、Access、PostgreSQL 或其他任何内容的 .NET 连接器,DataTableDataColumn 类始终相同并且是 ADO。 NET 对象是通用的,可以与任何数据库引擎一起使用,因此正如您所发现的,列的类型是 .NET 类型。

You cannot because System.Data.DataTable (or DataColumn, or DataSet, or DataRow...) is a generic .NET data container which works the same way regardless on the specific database engine you loaded your data from.

this means that provided you used a .NET Connector for SQL Server, MySQL, Access, PostgreSQL or anything else, the DataTable and DataColumn classes are always the same and being ADO.NET objects are generic to work with any db engine, so the columns are typed with the .NET types as you have found out.

鹤舞 2024-12-12 02:35:56
SqlConnection SqlCon = new SqlConnection("Data Source=(local);Database=dbname;Integrated Security=SSPI;");

SqlCon.Open();

SqlCmd = SqlCon.CreateCommand();
SqlCmd.CommandText = "select * from Tablename";

SqlDataReader SqlDr = SqlCmd.ExecuteReader();
SqlDr.Read();

int i = 0;

while (i < SqlDr.FieldCount)
{ 
   MessageBox.Show(SqlDr.GetDataTypeName(i));
   i++;
}
SqlConnection SqlCon = new SqlConnection("Data Source=(local);Database=dbname;Integrated Security=SSPI;");

SqlCon.Open();

SqlCmd = SqlCon.CreateCommand();
SqlCmd.CommandText = "select * from Tablename";

SqlDataReader SqlDr = SqlCmd.ExecuteReader();
SqlDr.Read();

int i = 0;

while (i < SqlDr.FieldCount)
{ 
   MessageBox.Show(SqlDr.GetDataTypeName(i));
   i++;
}
萌︼了一个春 2024-12-12 02:35:56

另一种方法是让 SQL 为您完成工作:

SqlConnection rConn = connectToSQL(); //returns sql connection
SqlCommand SqlCmd = new SqlCommand();
SqlCmd = rConn.CreateCommand();
SqlCmd.CommandText = "SELECT ORDINAL_POSITION, " +
                         "COLUMN_NAME, " +
                         "DATA_TYPE, " +
                         "CHARACTER_MAXIMUM_LENGTH, " +
                         "IS_NULLABLE " +
                    "FROM INFORMATION_SCHEMA.COLUMNS " +
                    "WHERE TABLE_NAME = 'TableName'";
SqlDataReader SqlDr = SqlCmd.ExecuteReader();
SqlDr.Read();
while (SqlDr.Read()) { 
    var OrdPos = SqlDr.GetValue(0);
    var ColName = SqlDr.GetValue(1);
    var DataType = SqlDr.GetValue(2);
    var CharMaxLen = SqlDr.GetValue(3);
    var IsNullable = SqlDr.GetValue(4);
    Console.WriteLine("ColName - " + ColName + " DataType - " + DataType + " CharMaxLen - " + CharMaxLen);
}

Another approach is to let SQL do the work for you:

SqlConnection rConn = connectToSQL(); //returns sql connection
SqlCommand SqlCmd = new SqlCommand();
SqlCmd = rConn.CreateCommand();
SqlCmd.CommandText = "SELECT ORDINAL_POSITION, " +
                         "COLUMN_NAME, " +
                         "DATA_TYPE, " +
                         "CHARACTER_MAXIMUM_LENGTH, " +
                         "IS_NULLABLE " +
                    "FROM INFORMATION_SCHEMA.COLUMNS " +
                    "WHERE TABLE_NAME = 'TableName'";
SqlDataReader SqlDr = SqlCmd.ExecuteReader();
SqlDr.Read();
while (SqlDr.Read()) { 
    var OrdPos = SqlDr.GetValue(0);
    var ColName = SqlDr.GetValue(1);
    var DataType = SqlDr.GetValue(2);
    var CharMaxLen = SqlDr.GetValue(3);
    var IsNullable = SqlDr.GetValue(4);
    Console.WriteLine("ColName - " + ColName + " DataType - " + DataType + " CharMaxLen - " + CharMaxLen);
}
等风也等你 2024-12-12 02:35:56

正如 David 所说……您在 .NET 中,因此类型将是 .NET 类型。这是从 SQL Server 到 .Net 的类型映射的列表,它向您展示了给定 Sql 列类型最终会得到的 .NET 类型..希望这会有所帮助..

http://msdn.microsoft.com/en-us/library/ms131092.aspx

As David says ... you are in .NET so the types will be .NET types. This is a listing of type mappings from SQL Server to .Net that shows you what .NET type you will end up with for a given Sql column type .. hope this helps ..

http://msdn.microsoft.com/en-us/library/ms131092.aspx

尝蛊 2024-12-12 02:35:56

根据 Madhukar Krishna 的回答,如果您有 SQLDataReaderMySQLDataReader 对象,您可以获得给定列的 SQL 类型元数据(在代码中,我们获得索引为 1 的列)使用以下代码(适用于 MySQLDataReader 对象的示例):

...
MySqlDataReader dr = ...
Console.WriteLine("dr.GetFieldType(1) = {0}, dr.GetName(1) = {1}, dr.GetValue(1) = {2}, dr.GetDataTypeName(1) = {3}", 
                          dr.GetFieldType(1), dr.GetName(1), dr.GetValue(1), dr.GetDataTypeName(1));
        bool b = Enum.TryParse(dr.GetDataTypeName(1), true, out System.Data.SqlDbType mySqlDbTypeEnum);
        Console.WriteLine("mySqlDbTypeEnum = {0}, b = {1}", mySqlDbTypeEnum, b);

该行:

bool b = Enum.TryParse(dr.GetDataTypeName(1), true, out System.Data.SqlDbType mySqlDbTypeEnum);

用于从 a 中获取 System.Data.SqlDbType String,并忽略字母大小写,例如,如果 dr.GetDataTypeName(1) 返回 "VARCHAR",则 System.Data. SqlDbType 枚举值为 System.Data.SqlDbType.VarChar。

然后,您可以通过使用以下代码检查 SQL 列元数据来获取数据类型的大小(例如 VARCHAR(15))(来源 MSDN):

... (continuation)
DataTable schemaTable;
// Retrieve column schema into a DataTable.
schemaTable = dr.GetSchemaTable();
// For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
{
   // For each property of the field...
   foreach (DataColumn myProperty in schemaTable.Columns)
   {
      // Display the field name and value.
      Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
   }
   Console.WriteLine();
   // Pause.
   //Console.ReadLine();
}

该属性ColumnSize 提供大小信息。

Building upon Madhukar Krishna's answer, if you have a SQLDataReader or a MySQLDataReader object you can obtain the SQL type metadata for a given column (in the code, we obtain the metadata of column with index 1) using the following code (example working for MySQLDataReader object):

...
MySqlDataReader dr = ...
Console.WriteLine("dr.GetFieldType(1) = {0}, dr.GetName(1) = {1}, dr.GetValue(1) = {2}, dr.GetDataTypeName(1) = {3}", 
                          dr.GetFieldType(1), dr.GetName(1), dr.GetValue(1), dr.GetDataTypeName(1));
        bool b = Enum.TryParse(dr.GetDataTypeName(1), true, out System.Data.SqlDbType mySqlDbTypeEnum);
        Console.WriteLine("mySqlDbTypeEnum = {0}, b = {1}", mySqlDbTypeEnum, b);

The line:

bool b = Enum.TryParse(dr.GetDataTypeName(1), true, out System.Data.SqlDbType mySqlDbTypeEnum);

is used to obtain the System.Data.SqlDbType from a String, and ignoring the letter case, e.g. if dr.GetDataTypeName(1) returns "VARCHAR" then the System.Data.SqlDbType enum value is System.Data.SqlDbType.VarChar.

Then, you can get get the size of the data type (for instance VARCHAR(15)) by inspecting the SQL columns metadata with the following code (source MSDN):

... (continuation)
DataTable schemaTable;
// Retrieve column schema into a DataTable.
schemaTable = dr.GetSchemaTable();
// For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
{
   // For each property of the field...
   foreach (DataColumn myProperty in schemaTable.Columns)
   {
      // Display the field name and value.
      Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
   }
   Console.WriteLine();
   // Pause.
   //Console.ReadLine();
}

The property ColumnSize gives the size information.

×眷恋的温暖 2024-12-12 02:35:56

如果您使用 DataReader -

SqlDataReader reader = cmd.ExecuteReader();
reader.GetDataTypeName(int ordinal)应该可以工作

如果您想要列的 SQL 数据类型,

If you are using DataReader -

SqlDataReader reader = cmd.ExecuteReader();
reader.GetDataTypeName(int ordinal)

should work if you want the SQL data type of a column

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文