簡體   English   中英

從sqlitereader c#遍歷數據集

[英]loop through dataset from sqlitereader c#

我通過這個從數據庫中獲取數據:

public static DataSet read_db(string sql)
    {
        DataSet ds = new DataSet();

        try
        {
            SQLiteConnection m_dbConnection;
            m_dbConnection = new SQLiteConnection("Data Source=movies.db;Version=3;");
            m_dbConnection.Open();
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

            //reader = command.ExecuteReader();
            using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
            {
                adapter.Fill(ds);
            }

            m_dbConnection.Close();
            return ds;
        }
        catch (SQLiteException ex)
        {
            string code = ex.Message.ToString();
            MessageBox.Show("Error connection to database: " + code);
            return ds;
        }
    }

現在,我試圖遍歷該數據集,並從數據庫中獲取值,使用的是來自sQLite的常規數據讀取器,但這無法正常工作,因為它將保持連接打開,直到我完成讀取為止,這意味着只要我的應用程序處於打開。

所以現在我必須將所有數據讀取器更改為使用數據集的方式,這是我以前的數據讀取器方式:

SQLiteDataReader reader = database.read_db("select * from proxies");
            while (reader.Read())
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(proxytable);
                row.Cells[0].Value = reader["id"];
                row.Cells[1].Value = reader["proxy"];
                row.Cells[2].Value = reader["port"];
                row.Cells[3].Value = reader["username"];
                row.Cells[4].Value = reader["password"];
                if (reader["dead"].ToString() == "0")
                { 
                    status = "ok";
                }
                else if(reader["dead"].ToString() == "2")
                {
                    status = "not tested";
                }
                else
                {
                    status = "ok";
                }
                row.Cells[5].Value = status;

                this.proxytable.Rows.Add(row);
            }

如何更改它以與數據集一起使用? 如果可能的話,只需進行很少的更改,因為我一直在使用此功能。

嘗試這樣...

        DataSet ds=  database.read_db("select * from proxies");                
        if (ds.Tables[0].Rows.Count > 0)
        {
        foreach (DataRow drw in ds.Tables[0].Rows)
        {

         DataGridViewRow row = new DataGridViewRow();
         row.CreateCells(proxytable);
         row.Cells[0].Value = drw ["id"];
         row.Cells[1].Value = drw ["proxy"];
         row.Cells[2].Value = drw ["port"];
         row.Cells[3].Value = drw ["username"];
         row.Cells[4].Value = drw ["password"];
        }
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM