MySQL query from C # returns InvalidOperationException

0

Thanks to the users I managed to establish the connection to my MySQL database from C #, but now another problem arose. I just want to get a DataSet where I can then read the data, but at the moment the function finishes, it always returns InvalidOperationException.

All variables are correctly initialized, and connection is the connection string. Artists is the name of one of the tables and albums is that of the other. Any extra information necessary do not hesitate to ask me.

Many thanks to those who bother to read my question, and even more to those who answer!

private void creaDataset()
    {
        conexion = new MySqlConnection(conexionn);
        try
        {
            conexion.Open();
            daArtists = new MySqlDataAdapter("SELECT*FROM ARTISTS", conexionn);
            daArtists = new MySqlDataAdapter("SELECT*FROM ALBUMS", conexionn);
            daArtists.Fill(ds, "Artists");
            daAlbums.Fill(ds, "Albums");
        }
        finally
        {

            conexion.Close(); 
        }
    }
    
asked by Denis Siks 14.11.2018 в 20:12
source

2 answers

2

You could try something like this

private DataSet creaDataset()
{
    var ds = new DataSet();
    using(MySqlConnection conexion = new MySqlConnection(conexionn))
    {
        conexion.Open();

        var daArtists = new MySqlDataAdapter("SELECT * FROM ARTISTS", conexion);
        daArtists.Fill(ds, "Artists");

        var daAlbums = new MySqlDataAdapter("SELECT * FROM ALBUMS", conexion);
        daAlbums.Fill(ds, "Albums");
    }
    return ds;
}

I highlight some points

  • when you define the select * from leaves a separation between the asterisk and the words
  • define different variable name for the dataadapter
  • define variables locally and not globally
  • when you assign the connection that is the object conexion and not the conexionn , I would recommend that you put something different variables in its name such as changing conexionn by connexionString or something like that
answered by 14.11.2018 / 20:46
source
0

It would be as follows:

private void creaDataset()
{
    conexion = new MySqlConnection(conexionn);
    try
    {
        MySqlCommand comando = new MySqlCommand("SELECT*FROM ARTISTS", conexion);
        MySqlDataAdapter adaptador = new MySqlDataAdapter(comando);
        adaptador.Fill(daArtists);

        comando = new MySqlCommand("SELECT*FROM ALBUMS", conexion);
        adaptador = new MySqlDataAdapter(comando);
        adaptador.Fill(daAlbums);
    }
    catch (Exception ex)
    {

    }
}
    
answered by 14.11.2018 в 20:22