fxfuture
fxfuture

Reputation: 1950

Get array of database field names in C#?

What's the simplest way to get a string array of database field names? I tried using SHOW COLUMNS but I couldn't get it to work.

I'm currently doing it this way:

private List<string> GetDBFieldNames()
{
    List<string> dbFieldNames = new List<string>();
    try {
        System.Data.SqlClient.SqlConnection con = d.connectDB();
        String query = "select * from my_table";
        SqlDataAdapter cmd = new SqlDataAdapter(query, con);

        DataTable dt = new DataTable();
        cmd.Fill(dt);

        foreach(DataColumn column in dt.Columns) {
            dbFieldNames.Add(column.ColumnName);
        }
    }
    catch (Exception ex) {}

    return dbFieldNames;
}

Upvotes: 2

Views: 1225

Answers (1)

devmb
devmb

Reputation: 805

I think the easiest way to get the colmn names ist to select them from INFORMATION_SCHEMA as mentioned here. You can go with the following SQL statement:

SELECT COLUMN_NAME,* 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND TABLE_SCHEMA='SchemaName'

Upvotes: 3

Related Questions