Show databases of MySql server

11,525

Solution 1

string myConnectionString = "SERVER=localhost;UID='root';" + "PASSWORD='root';";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SHOW DATABASES;";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
  string row = "";
  for (int i = 0; i < Reader.FieldCount; i++)
       row += Reader.GetValue(i).ToString() + ", ";
       comboBox1.Items.Add(row);
}
connection.Close();

Solution 2

SqlConnection conn = new SqlConnection(ConnectionString);

SqlCommand com = new SqlCommand ("show databases",conn);
conn.Open();
SqlDataReader reader = com.ExecuteReader();
DataTable dt = new DataTable;
dt.Load(reader);
DataRows[] rows = dt.Rows;

Think you can then view the data rows

That said, if you already have the connection string, there's no reason not to open MSqlServer or whatever and view it from there...

Share:
11,525
user35443
Author by

user35443

Updated on June 08, 2022

Comments

  • user35443
    user35443 almost 2 years

    Does anybody know, how to show databases in C#? I know thats possible by executing a sql command show databases, but i dont know how to configure reader. Anybody please help me.

    EDIT: I found a solution:

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MySqlConnection con = new MySqlConnection(this.constr);
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "show databases";
            try
            {
                con.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    string row = "";
                    for (int i = 0; i < reader.FieldCount; i++)
                        row += reader.GetValue(i).ToString();
                    listBox1.Items.Add(row);
                }
    
    
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Number.ToString());
                MessageBox.Show(ex.Message);
            }
    
        }