locked
How can I identify the column names and datatypes of a datatable in MySQL database using c# RRS feed

  • Question

  • User-1313756816 posted

    I want to be able to query a mysql database...knowing the tablename...but not knowing the column in that table or their datatypes and size restrictions and be able to retrieve that information... 

    How can I do that in c#?

    Tuesday, February 28, 2012 5:03 PM

Answers

  • User665793701 posted

    Dear Prysson,

    Try this sql from your c# code

    "SHOW COLUMNS FROM mytable FROM mydb";

    then iterate the returned data and fetch your desired column name and data type.

    Regards,
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 29, 2012 4:51 AM
  • User-1313756816 posted

    Thanks for the Query.  Works like a charm.

    Anyone who may not know how to evaluate the data in c# as its returned from the query the following will work

    MySqlConnection msql = new MySqlConnection();
    msql.ConnectionString = "connectionstringinfo";

    MySqlDataAdapter myAdapter = new MySqlDataAdapter("SHOW COLUMNS FROM mytable", msql);

    DataSet ds = new DataSet();
    ds.Tables.Add(dt);
    myAdapter.Fill(ds.Tables[0]);

    DataTable dt = ds.Table[0];

     then parse through the datatable columns and you will have yoru column names and data types.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 29, 2012 6:49 PM

All replies

  • User665793701 posted

    Dear Prysson,

    Try this sql from your c# code

    "SHOW COLUMNS FROM mytable FROM mydb";

    then iterate the returned data and fetch your desired column name and data type.

    Regards,
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 29, 2012 4:51 AM
  • User-1313756816 posted

    Thanks for the Query.  Works like a charm.

    Anyone who may not know how to evaluate the data in c# as its returned from the query the following will work

    MySqlConnection msql = new MySqlConnection();
    msql.ConnectionString = "connectionstringinfo";

    MySqlDataAdapter myAdapter = new MySqlDataAdapter("SHOW COLUMNS FROM mytable", msql);

    DataSet ds = new DataSet();
    ds.Tables.Add(dt);
    myAdapter.Fill(ds.Tables[0]);

    DataTable dt = ds.Table[0];

     then parse through the datatable columns and you will have yoru column names and data types.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 29, 2012 6:49 PM