简体   繁体   中英

c# How can I filter the column names of a database table?

I have used the INFORMATION_SCHEMA to get all tables and columns of my database.

DataTable dt_search_BaseTables = new DataTable();
MySqlDataAdapter mAdapter;
MySqlCommand myCommand = new MySqlCommand(@"SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, 
                                            COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM 
                                            INFORMATION_SCHEMA.COLUMNS", connection);
mAdapter = new MySqlDataAdapter(myCommand);
mAdapter.Fill(dt_search_BaseTables);

But if I want to select a specific table_name to get only the columns of one table that doesn't work:

DataRow[] dr = dt_search_BaseTables.Select("TABLE_NAME=" + stablename);

I get the

ERROR: The column [stablename] could not be found.

How can I solve that problem?

The issue is quite simple: you need to add single quotes around the passed table name inside stablename , then it treated the passed value as string literal assignment due to Select method has same expression rule as RowFilter syntax .

Therefore it should be like this:

DataRow[] dr = dt_search_BaseTables.Select("TABLE_NAME = '" + stablename + "'");

or create a string variable then pass it into Select method:

string expression = "TABLE_NAME = '" + stablename + "'";
DataRow[] dr = dt_search_BaseTables.Select(expression);

Reference:

DataTable.Select Method (MSDN)

I'd suggest you to add WHERE condition to the SELECT query. It will help to filter a huge set of unnecessary tables on server side -

For example -

SELECT
  TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY
FROM
  INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM