How to get the SqlType of a column in a DataTable?

前端 未结 7 424
予麋鹿
予麋鹿 2020-12-31 01:45

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

using (SqlCommand cmd = new SqlCommand(query, _sqlserverDB))
{
    using (SqlDataAdapter adapter          


        
相关标签:
7条回答
  • 2020-12-31 02:22

    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.

    0 讨论(0)
提交回复
热议问题