需要找到DB列的类型

时间:2010-08-05 17:42:05

标签: c# sql database

这是我的一段代码。我得到了数据库中存在的所有表名和列名。现在我需要知道列的类型。比如它的int或varchar或其他什么。可以帮助我这个??顺便说一句,这是C#。

OleDbConnection con = new OleDbConnection(connectionString);
DataTable schemaCols;
DataTable schemaTbl;
List<string> tablesnames = new List<string>();
string returnString="";

try
{
    con.Open();
    object[] objArrRestrict;
    objArrRestrict = new object[] { null, null, null, "TABLE" };
    schemaTbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, objArrRestrict);
    foreach (DataRow row in schemaTbl.Rows)
    {
        tablesnames.Add(row["TABLE_NAME"].ToString());
    }
    List<string> columnnames = new List<string>();
    foreach (string str in tablesnames)
    {
         string selTbl = str;

        //con.Open();
        object[] objArrRestrictNew;
        objArrRestrictNew = new object[] { null, null, selTbl, null };
        //
        schemaCols = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, objArrRestrictNew);

        foreach (DataRow row in schemaCols.Rows)
        {
            columnnames.Add(row["COLUMN_NAME"].ToString());

        }
     }
   }

4 个答案:

答案 0 :(得分:5)

您也可以从OleDb

中检索列类型
DataTable schemaTable = connection.GetOleDbSchemaTable(
    System.Data.OleDb.OleDbSchemaGuid.Columns,
    new object[] { null, null, null, null });

schemaTable的DATA_TYPE列包含一个可以强制转换为OleDbType

的整数

如果您需要数据类型,可以使用类似于此的转换函数(我将此用于mdb和accdb文件,但我知道它应该被增强)

    private static string ConvertToJetDataType(int oleDbDataType)
    {
        switch (((OleDbType)oleDbDataType))
        {
            case OleDbType.LongVarChar:
                return "varchar";
            case OleDbType.BigInt:
                return "int";       // In Jet this is 32 bit while bigint is 64 bits
            case OleDbType.Binary:
            case OleDbType.LongVarBinary:
                return "binary";
            case OleDbType.Boolean:
                return "bit";
            case OleDbType.Char:
                return "char";
            case OleDbType.Currency:
                return "decimal";
            case OleDbType.DBDate:
            case OleDbType.Date:
            case OleDbType.DBTimeStamp:
                return "datetime";
            case OleDbType.Decimal:
            case OleDbType.Numeric:
                return "decimal";
            case OleDbType.Double:
                return "double";
            case OleDbType.Integer:
                return "int";
            case OleDbType.Single:
                return "single";
            case OleDbType.SmallInt:
                return "smallint";
            case OleDbType.TinyInt:
                return "smallint";  // Signed byte not handled by jet so we need 16 bits
            case OleDbType.UnsignedTinyInt:
                return "byte";
            case OleDbType.VarBinary:
                return "varbinary";
            case OleDbType.VarChar:
                return "varchar";
            case OleDbType.BSTR:
            case OleDbType.Variant:
            case OleDbType.VarWChar:
            case OleDbType.VarNumeric:
            case OleDbType.Error:
            case OleDbType.WChar:
            case OleDbType.DBTime:
            case OleDbType.Empty:
            case OleDbType.Filetime:
            case OleDbType.Guid:
            case OleDbType.IDispatch:
            case OleDbType.IUnknown:
            case OleDbType.UnsignedBigInt:
            case OleDbType.UnsignedInt:
            case OleDbType.UnsignedSmallInt:
            case OleDbType.PropVariant:
            default:
                throw new ArgumentException(string.Format("The data type {0} is not handled by Jet. Did you retrieve this from Jet?", ((OleDbType)oleDbDataType)));
        }
    }

答案 1 :(得分:3)

您可以使用OleDbCommand.ExecuteReader来读取您找到的每个表的架构。

    OleDbConnection con = new OleDbConnection(connectionString);
    DataSet tablesFromDB = new DataSet();
    DataTable schemaTbl;
    try
    {
        // Open the connection
        con.Open();
        object[] objArrRestrict = new object[] { null, null, null, "TABLE" };

        // Get the table names from the database we're connected to
        schemaTbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, objArrRestrict);

        // Not sure if this is correct syntax...fix it if it isn't :)
        String commandText = @"SELECT * FROM {0}";

        // Get each table name that we just found and get the schema for that table.
        foreach (DataRow row in schemaTbl)
        {
            DataTable dt = new DataTable();
            OleDbCommand command = new OleDbCommand(String.Format(commandText, row["TABLE_NAME"] as String), con);
            dt.Load(command.ExecuteReader(CommandBehavior.SchemaOnly));
            tablesFromDB.Tables.Add(dt);
        }
    }

这样,您可以遍历DataSet的DataTable集合并获取列名和列字段类型。

foreach (DataTable dt in tablesFromDB)
{
    foreach (DataColumn dc in dt.Columns)
    {
        // Do something with the column names and types here
        // dc.ColumnName is the column name for the current table
        // dc.DataType.ToString() is the name of the type of data in the column
    }
}

可能有更好的方法,但我认为这是一个开始。

答案 2 :(得分:0)

答案 3 :(得分:0)

试试这个:(不需要使用SQL的select语句)

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dataSource;
OleDbConnection connection = new OleDbConnection(connectionString);

DataTable schemaTable = null;
string tblName = "xxx";
try
{
    connection.Open();
    //obtain column information in table "xxx"
    schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tblName, null });

}
catch (Exception ex)
{
    String str = ex.Message;
}
finally
{
    connection.Close();
}


foreach (DataRow row in schemaTable.Rows)
{
    columnNames.Add(row["COLUMN_NAME"].ToString());
    DataColumn colnum_type = row.Table.Columns["DATA_TYPE"] as DataColumn;  //note this line
    ColumnDataTypes.Add(colnum_type.DataType);
}