2017-12-27 777 views
1

我有我的sqlite數據庫存儲在C:\program-name\db\db.s3db。 我有一個表members與約70記錄。所以現在有一個我必須做的程序,它將所有賬號從members表複製到另一個表act_monthly_listingsSQLite數據庫與C#執行非常緩慢

它顯示它正在執行,但它的速度很慢。我不知道是否因爲我的代碼。這裏是一個片段:

連接:

private void SetConnection() 
     { 
      sql_con = new SQLiteConnection 
       ("Data Source=C:\\credit-union\\db\\cu.s3db;Version=3;New=False;Compress=True;"); 
     } 

在ButtonClick代碼:

private void button1_Click(object sender, EventArgs e) 
     { 

     button1.Text = "Working Please Wait"; 
     string init_month = dtInit.Value.Month.ToString(); 
     string init_yr = dtInit.Value.Month.ToString(); 

     SetConnection(); 
     sql_con.Open(); 

     SQLiteCommand cmd = new SQLiteCommand(); 
     cmd.CommandText = "select ec_no from members"; 
     cmd.Connection = sql_con; 

     DR = cmd.ExecuteReader(); 

     int count = 0; 

     while (DR.Read()) 
     { 
      DR.Read(); 
      this.Text = "Account : " + DR.GetInt32(0).ToString(); 
      string SQL = "INSERT INTO act_monthly_listings (year,month,act) VALUES ("+ init_yr + "," + init_month + "," + DR.GetInt32(0).ToString() + ")"; 
      //Clipboard.SetText(SQL) 
      if (ExecuteQuery(SQL)) 
      { 
       count++; 
      } 


     } 

     if(count > 0){ 
      MessageBox.Show("Accounts Initialized!", "Success", MessageBoxButtons.OK,MessageBoxIcon.Information); 
     }else{ 
      MessageBox.Show("Initialization Failed!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 
     sql_con.Close(); 
    } 
+0

這可能是因爲'while',爲什麼不使用'INSERT INTO -SELECT'來在一次拍攝中完成所有這些操作。 – Aria

+1

如果它確實起作用,那麼你只能得到其他所有行,因爲你調用了'Read()'兩次。 – Crowcoder

回答

4

那是因爲while您正在執行insert查詢等於行數,使您的程序運行速度很慢所以這最好用 INSERT INTO-SELECT like:

 string init_month = dtInit.Value.Month.ToString(); 
    string init_yr = dtInit.Value.Month.ToString(); 
    SQLiteCommand cmd = new SQLiteCommand(); 
    cmd.CommandText = "INSERT INTO act_monthly_listings (year,month,act) select @y,@m,ec_no from members"; 
    cmd.Parameters.Add(new SQLiteParameter("@y", init_yr)); 
    cmd.Parameters.Add(new SQLiteParameter("@m", init_month)); 
    cmd.Connection = sql_con; 
    cmd.ExecuteNonQuery(); 

所有行插入一個拍攝,當您使用while直到reader.Read()指針抵達最後一排的DataReader與DB連接(需活着連接),可能使連接池慢,再加上你正在執行每Read避免查詢這個, 假設你有一百萬條記錄,那麼你的代碼發生了什麼?

+0

像魔術一樣。謝謝Bro – kingraphaII

+0

非常歡迎。 – Aria