Looking for some C# examples that can retrieve the tables' names from a specific database on a server. I already have a valid connection string, just looking for the right way of adding the names of each table into List for later retrieval and manipulation.
MySQL SHOW TABLES command example To use the SHOW TABLES command, you need to log on to the MySQL server first. On opening the MySQL Command Line Client, enter your password. Select the specific database. Run the SHOW TABLES command to see all the tables in the database that has been selected.
First, enable Object Explorer Details going to View > Object Explorer Details or by pressing F7 buton. Now, select Tables element in your database in Object Explorer. List of tables with details will show in in the right pane in Object Explorer Details tab.
System.Data.SqlClient
has what you need without a formal query on sys.Tables (though that's what it's using in the background). Use the GetSchema()
method on the SqlConnection
object and designate that you want the "Tables" and it will send you a DataTable
object back with a row for each table. It sends back database name, table schema name, table name, and table type in each row (in that column order). The code would look like this:
public static List<string> GetTables(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
DataTable schema = connection.GetSchema("Tables");
List<string> TableNames = new List<string>();
foreach (DataRow row in schema.Rows)
{
TableNames.Add(row[2].ToString());
}
return TableNames;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With