How can I get List<string>
of all table names contained in a MySQL database?
I want to load a complete database into a DataSet but from my understanding it seems that MySqlDataAdapter.Fill() only operates on single tables, correct? That is what I want to use the table string collection for.
EDIT:
I look for the correct query: The following returns 59 different items despite the database only holding 3 tables:
MySqlCommand command = new MySqlCommand("SELECT table_name FROM information_schema.tables where table_type = 'BASE TABLE'", connection);
var result = command.ExecuteReader();
I look for C# code to parse the result of the query into a List<string>
.
Use Entity fraemwork, add your schema to the dbcontext then you can make something like:
var tableNames = context.MetadataWorkspace.GetItems(DataSpace.SSpace)
.Select(t => t.Name)
.ToList();
EDIT:
Alternativly you can read the tablen names using a normal sql query (for example using Show tables) and parse these into a list like:
List<String> Tablenames = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
string query = "show tables from YourDB";
SqlCommand command = new SqlCommand(query, connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Tablenames.Add(reader.GetString(0));
}
}
}
Download and install Connector/Net first.This is necessary to use MySQL in C# .MySQL for Visual Studio is not necessary,but I recommend you to install it.It can help you designing MySQL databases in Visual Studio.
Add reference to MySql.Data
Add using MySql.Data.MySqlClient;
in your code.
Declare a function like this:
public List<string> MySqlCollectionQuery(MySqlConnection connection, string cmd)
{
List<string> QueryResult = new List<string>();
MySqlCommand cmdName = new MySqlCommand(cmd, connection);
MySqlDataReader reader = cmdName.ExecuteReader();
while (reader.Read())
{
QueryResult.Add(reader.GetString(0));
}
reader.Close();
return QueryResult;
}
Then create a MySql connection and call this function:
string connStr = string.Format("user={0};password={1};database={2}",
username,password,database);
List<string>TableNames = new List<string>();//Stores table names in List<string> form
using(MySqlConnection Conn = new MySqlConnection(connStr))
{
Conn.Open();
string cmdStr = "show tables";
TableNames = MySqlCollectionQuery(Conn,cmdStr);
}
I did not put this in a try ... catch
block,but it is always a good practice to do that.
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