2

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;
}
fxfuture
  • 1,910
  • 3
  • 26
  • 40

1 Answers1

3

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'
Community
  • 1
  • 1
devmb
  • 805
  • 6
  • 18
  • Thanks but would I still fill a datatable with this? Doesn't work if I just replace the sql statement – fxfuture Apr 09 '14 at 21:31
  • You just get the column names. Did you replace TabelName and SchemaName? Please update your code example. – devmb Apr 09 '14 at 21:44
  • I got it working. I just needed to get the rows instead of column names with `string field = dt.Rows[i][0].ToString();` – fxfuture Apr 15 '14 at 17:36