jeudi 23 juillet 2015

Using SQLiteCommand and SQLiteDataReader in same foreach loop for multiple times

In my WPF application i ve to use SQLiteCommand and SQLiteDataReader multiple times in same foreach loop. Here is how i am doing but its not working as expected. I am expecting to get all the records from ArtistSong_tbl which match the song_cord_ids datas. But for now i only got single record. Here is code.

try
        {
            conn.Open();
            var command = conn.CreateCommand();
            command.CommandText = "SELECT song_id FROM fav_tbl";
            SQLiteDataReader sdr = command.ExecuteReader();

            while(sdr.Read())
            {
                song_cord_ids.Add(sdr.GetString(0));
            }
            sdr.Close();

            if(song_cord_ids.Count>0)
            {

                foreach (var songId in song_cord_ids)
                {
                    command.CommandText = "SELECT * FROM ArtistSong_tbl WHERE Artist_id='" + songId + "'";

                    SQLiteDataReader sdr1 = command.ExecuteReader();
                    if (sdr1.HasRows)
                    {
                        while (sdr1.Read())
                        {
                            favsongs.Add(new Song()
                            {
                                _id = sdr1.GetString(1),
                                title = Crypto_Engine.Decrypt(sdr1.GetString(2), "songcord-ekbana-crypto11"),
                                isTabs = sdr1.GetString(3)
                            });
                        }
                    }
                    else
                    {
                        //ToDo visibility control
                    }
                    sdr1.Close();
                }
                this.FavSongs = favsongs.OrderBy(s=> s.title).ToList();
            }
        }

So in code i have foreach loop and in that loop i am getting specific songs(by songs id) from database so when loop starts for 1 time it works fine after that at bottom i closed sdr1(SQLiteDataReader variable) so in next loop command.ExecuteReader() doesn't work because sdr1 variable is closed already and if i didn't close that then i am unable to load another command and execute while sdr1 is still open. So how can i make it work?

Aucun commentaire:

Enregistrer un commentaire