C#操作SQLite數據庫

採用DevExpress公司的開發框架XAF編寫出具有數據導入和導出功能的模塊,實現的主要功能如下:

1)將MS SQL Server數據庫中的數據導出到MS Excel文件;

2)將MS SQL Server數據庫中數據導出SQLite數據庫文件;

3)從SQLite數據庫文件中導入數據到MS SQL Server數據庫;

其中導出到Excel中的功能已經在前面寫過了。


從SQL Server數據庫中導出數據到SQLite的主要功能代碼如下:

public void Export(string filename, CriteriaOperator criteria)
        {
            IList<Data> ds = os.GetObjects<Data>(criteria);
            SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder() { DataSource = filename };
            SQLiteConnection conn = new SQLiteConnection() { ConnectionString = connstr.ConnectionString };
            conn.Open();
            createDataTable(ref conn);
            rows = insertData(ref conn, ds);
            conn.Close();
        }

        private void createDataTable(ref SQLiteConnection conn)
        {
            using (SQLiteCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = @"CREATE TABLE Data(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, time TEXT, data NONE)";
                cmd.ExecuteNonQuery();
                //cmd.CommandText = @"DROP TABLE Data";
                //cmd.ExecuteNonQuery();
            }
            if (ReportProgress != null)
                ReportProgress(100);
        }

        private int insertData(ref SQLiteConnection conn, IList<Data> ds)
        {
            int result = 0;
            using (var transaction = conn.BeginTransaction())
            {
                using (SQLiteCommand cmd = new SQLiteCommand(conn))
                {
                    string sqlInsert = "INSERT INTO Data(time, data) VALUES('time', 'data')";
                    StringBuilder sb = new StringBuilder(sqlInsert);
                    Sencoding scod = new Sencoding(); //Sencoding是自定義類
                    foreach (var item in ds)
                    {
                        result++;
                        sb.Replace(sb.ToString().Substring(36),
                            string.Format("'{0}', '{1}')", item.Time, scod.GetString(item.Datagram)));
                        cmd.CommandText = sb.ToString();
                        cmd.ExecuteNonQuery();
                        if (ReportProgress != null)
                            ReportProgress(result * 9800 / ds.Count + 100);
                        if (cancel) break;
                    }
                }
                if (cancel)
                {
                    transaction.Rollback();
                    result = 0;
                    if (ReportProgress != null)
                        ReportProgress(100);
                }
                else
                {
                    transaction.Commit();
                    if (ReportProgress != null)
                        ReportProgress(10000);
                }
            }
            return result;
        }

SaveFileDialog sfd = new SaveFileDialog()
                        {
                            InitialDirectory = Environment.CurrentDirectory,
                            RestoreDirectory = true,
                            Filter = "Sqlite Databse Files(*.db)|*.db",
                            FileName = "SFDRMS.db"
                        };
                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            BackgroundWorker bgw = new BackgroundWorker();
                            bgw.WorkerReportsProgress = true;
                            bgw.DoWork += (bender, be) =>
                            {
                                IObjectSpace os = be.Argument as IObjectSpace;
                                SqliteIE sqlite = new SqliteIE(os);
                                sqlite.ReportProgress += bgw.ReportProgress;
                                try
                                {
                                    sqlite.Export(sfd.FileName, null);
                                }
                                finally
                                {
                                    be.Result = sqlite.AffectedRows;
                                }
                            };
                            bgw.ProgressChanged += (bsender, be) =>
                            {
                                SplashScreenManager.Default.SetWaitFormDescription(string.Format("{0, 5:G}%", be.ProgressPercentage / 100.0));
                            };
                            bgw.RunWorkerCompleted += (bsender, be) =>
                            {
                                SplashScreenManager.Default.SetWaitFormDescription(string.Format("Affected Rows: {0}", (long)be.Result));
                                SplashScreenManager.Default.CloseWaitForm();
                                SplashScreenManager.CloseForm(false);
                            };
                            bgw.RunWorkerAsync(Application.CreateObjectSpace());
                            SplashScreenManager.ShowForm(typeof(MyWaitForm), true, true);
                            SplashScreenManager.Default.SetWaitFormCaption("Exporting...");
                        }


使用ObjectSpace將SQLite數據庫中數據導入SQL Server數據庫中

public void Import(string filename)
        {
            using (SQLiteConnection conn = new SQLiteConnection())
            {
                conn.ConnectionString = "data source = " + filename;
                conn.Open();
                using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Data ORDER BY id", conn))
                {
                    SQLiteDataReader dataReader = cmd.ExecuteReader();
                    rows = newData(dataReader);
                    dataReader.Close();
                }
                conn.Close();
            }
        }

        private long newData(SQLiteDataReader dataReader)
        {
            long result = 0;
            Sencoding scod = new Sencoding();
            while (dataReader.Read())
            {
                result++;
                DateTime time = DateTime.Parse(dataReader.GetString(1));
                byte[] data = scod.GetBytes(dataReader.GetString(2));
                Data d = os.CreateObject<Data>();
                d.Time = time;
                d.Datagram = data;
                if (cancel)
                {
                    break;
                }
                d.Save();
            }
            if (!cancel)
            {
                os.CommitChanges();
            }
            else
            {
                result = 0;
            }
            return result;
        }

OpenFileDialog ofd = new OpenFileDialog()
                        {
                            InitialDirectory = Environment.CurrentDirectory,
                            RestoreDirectory = true,
                            Filter = "SQLite Database Files(*.db)|*.db"
                        };
                        if (ofd.ShowDialog() == DialogResult.OK)
                        {
                            BackgroundWorker bgw = new BackgroundWorker();
                            bgw.DoWork += (bender, be) =>
                            {
                                IObjectSpace os = be.Argument as IObjectSpace;
                                SqliteIE sqlite = new SqliteIE(os);
                                sqlite.Cancel = true;
                                try
                                {
                                    sqlite.Import(ofd.FileName);
                                }
                                finally
                                {
                                    be.Result = sqlite.AffectedRows;
                                }

                            };
                            bgw.RunWorkerCompleted += (bender, be) =>
                            {
                                long affectedRows = (long)be.Result;
                            };
                            bgw.RunWorkerAsync(Application.CreateObjectSpace());
                        }

另附:

Visual Studio中添加SQLite的方法:

添加後:

DevExpress中的ProgressBarControl:




發佈了43 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章