我的sqlite
数据库存储在C:\program-name\db\db.s3db
中。
我有一张表members
,其中包含约70
条记录。所以现在我需要做一个程序,即将所有帐号从members
表复制到另一个表act_monthly_listings
。
它显示它正在执行,但它的速度非常慢。我不知道是不是因为我的代码。这是一个片段:
连接:
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=C:\\credit-union\\db\\cu.s3db;Version=3;New=False;Compress=True;");
}
On 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 :(得分:4)
那是因为while
你正在执行insert
查询等于行数,这会使你的程序运行得非常慢,所以最好使用
INSERT INTO-SELECT
喜欢:
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
执行查询,避免这种情况,
假设你有一百万条记录然后你的代码发生了什么?