如何从一个列表中的数据表返回数据类型?

时间:2011-03-13 05:13:44

标签: c# ado.net

我有一个数据表,它给我列的列名,数据类型和最大字符长度。 returntype应该是一个列表,我如何只在一个列表中链接列名和数据类型。请帮助。

 try
        {
            List<string> tablelist = new List<string>();
            DataTable dt;
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT column_name,data_type,character_maximum_length FROM "+ dbPropertiesobj.DBName +".information_schema.columns WHERE table_name = '"+ TableName+"' ", conn);
            SqlDataAdapter sqlda = new SqlDataAdapter(cmd);
            dt = new DataTable();
            sqlda.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string dtrow = dt.Rows[i].ItemArray[0].ToString(); //gets only the columnname
                tablelist.Add(dtrow);
            }
            return tablelist; // need the datatype and maximum character length along with the name.
        }
        catch (Exception ex)
        {
            return null;
        }

2 个答案:

答案 0 :(得分:1)

为什么不是3-Tuple对象的列表(即具有3个值的元组)?不确定声明List的确切语法,但每个条目都是这样的:

Tuple.Create(column_name, datatype, max_length)

答案 1 :(得分:1)

你有很多东西正在使用这段代码。我完全重写了它,这不是最短的代码,甚至不是最好的方法,但它是为了说明要学习更多或工作的领域。

研究异常处理,特别是何时使用它以及如何使用它。永远不要编写吞下错误的try块。如果此方法返回null,您打算做什么?桌名不好吗?连接失败了吗?用户可能会或可能不会修复错误,但您吞下了它。现在没有人知道它是什么。

更糟糕的是,根据你对null做了什么,可能没有人知道这里发生的错误。永远不要吞下这样的错误。应用程序应在发生错误的位置失败。还要注意返回这样的空值。当您返回空值然后执行其他操作时,应用程序可能会在某个地方失败,而原始错误现在更难找到并修复。在编写框架时,您可能偶尔会以此样式返回null。对于普通应用,通常不需要它,几乎从来不是一个好主意。

高质量的生产代码通常包含非常少的异常处理,因为您应该使用条件来处理您可以预期的任何事情。你无法预料到的任何东西通常也无法处理。你可能有很多尝试... finally块存在以清理资源,但应用程序应该包含很少的实际try..catch黑色。通常,您将错误传播回调用堆栈,返回到最终处理程序,以便在应用程序关闭之前通知用户。

以下仍然不是您能写的最佳代码。我把它保持在合理的原始状态,并删除了一些捷径,以使其更清晰。研究差异并从那里开始

public class SomeClass
{

    //Use parameters rather than accessing module level properties
    private IList<ColumnInformation> GetColumnInformationForTable(string dbName, string tableName)
    {
        // Favor object oriented styles and meaningful names.  Your method does not return a list of tables
        // it returns a list of column meta data
        List<ColumnInformation> columnInformations = new List<ColumnInformation>();

        // Avoid SQL conncatenation if at all possible.  NEVER concatenate where parameters into SQL commands and NEVER EVER with single quotes.
        // Here table name requires concatenation but the select parameter TableName does not.
        string selectCmdString = "SELECT column_name,data_type,character_maximum_length FROM " + dbName + ".information_schema.columns WHERE table_name = @TableName";

        // Use parameters.  Get everything ready first, don't open connections prematurely and only wrap error prone code in try blocks.
        SqlCommand cmd = new SqlCommand(selectCmdString, conn);
        SqlParameter tableNameParameter = new SqlParameter("@TableName", tableName);
        cmd.Parameters.Add(tableNameParameter);

        // Use a DataReader since you cannot modify this data anyway.
        // This also shows an appropriate use of a try block to ensure a connection gets closed, 
        // but better yet, open your reader with the CommandBehavior set to close
        // and get rid of this try block altogether
        try
        {
            //Reconsider use of a module or global level connection.  May be better to create a new here.
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            //Favor OOP styles rather than indexes and arrays and repeated calls to determine things like Rows.Count in a loop 
            while(reader.Read())
            {
                // Favor explicit member access rather than index acess.
                //YOUR HOMEWORK!  Study DataReader access and rewrite the code below to handle possible nulls in length field.  Use a method based on evaluating conditionals, DO NOT use a method based on a try block.
                ColumnInformation columnInformation = new ColumnInformation(reader["column_name"].ToString(), reader["data_type"].ToString(), (int)reader["character_maximum_length"].ToString());
                columnInformations.Add(columnInformation);
            }
            reader.Close();
        }
        finally
        {
            // The only reason to use the try is to make sure the connection gets closed here.  A better approach
            // is to use the CommandBehavior.CloseConnection option and get rid of the try finally block completely.
            // But NEVER just wrap a bunch of code in try blocks arbitrarily, swallow any errors and return a null.
            conn.Close();
        }


        return columnInformations;
    }


}

public class ColumnInformation
{
    private string _columnName;
    private string _dataType;
    private int _columnLength;

    public string ColumnName
    {
        get { return _columnName; }
    }

    public string DataType
    {
        get { return _dataType; }
    }

    public int ColumnLength
    {
        get { return _columnLength; }
    }

    public ColumnInformation(string columnName, string dataType, int columnLength)
    {
        _columnName = columnName;
        _dataType = dataType;
        _columnLength = columnLength;
    }
}