c# - SQLite 数据库与 C# 执行速度非常慢

标签 c# .net database sqlite

我的 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;");
        }

在 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(); 
    }

最佳答案

那是因为 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 的查询,避免这种情况, 假设您有一百万条记录,那么您的代码发生了什么?

关于c# - SQLite 数据库与 C# 执行速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992759/

相关文章:

c# - 在 WebBrowser 控件中禁用 JavaScript 错误

python - 用于 python 程序的中大型可移植数据库选项

ios - applicationDidEnterBackground : and time to write on a database

.net - 来自PowerShell的.Net SQL Server查询

c# - 监视超时的同步方法

c# - 如何通过https获取隐藏文件的内容?

c# - PrintDialog/XPS Document Writer 中忽略的纸张大小

c# - 通过 WMI 确定网络适配器类型

c# - 如何在 RavenDB 上查询子元素?

c# - 如何在单个应用程序中使用多个域? ASP.net core 3.0( Razor 页面, azure )