C#與Sqlite數據庫操作實例

這是一個有關分頁的實例,僅供參考(代碼來自網絡)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.Threading;
using System.Collections;
using System.IO;

namespace ReadCardDemo
{
    public partial class Form3 : Form
    {
        Form4 form4 = new Form4();
        int pageSize = 12;     //每頁顯示行數
         int nMax = 0;         //總記錄數
         int totalPage = 0;    //總頁數=總記錄數/每頁顯示行數
         int currentPage = 1;   //當前頁號
         int pageCount = 0;    //當前頁數的記錄數
         int selectRow; //當前選中的行數
         DataSet dataSet = new DataSet();
        DataTable dataTable = new DataTable();
        SQLiteDataAdapter dataAdapter;
        SQLiteConnection conn = new SQLiteConnection();
        SQLiteCommand cmd;
        SQLiteDataReader dr;
        string datasource;
        string _sql;

        public Form3()
        {
            InitializeComponent();            
        }

        //初始化數據
        public void InitializeDataSource()
        {
            dataTable.Clear();
            dataTable.AcceptChanges();
            //創建數據庫
            //datasource = "/Windows/ReadCardDemo/PersonId.db";
            //SQLiteConnection.CreateFile(datasource);

            //建立數據庫連接
            datasource = @"Data Source=/Windows/ReadCardDemo/PersonId.db";
            conn.ConnectionString = datasource;
             //獲取當前數據庫的記錄數
            _sql = "select count(*) from PersonId";
            conn.Open();
            cmd = new SQLiteCommand(_sql, conn);            
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                try
                {
                    nMax = Convert.ToInt32(dr.GetValue(0));
                }
                catch(Exception e)
                {
                    MessageBox.Show("計算總頁數出錯!類型轉換錯誤"+e.Message);
                }
            }
            dr.Close();
            conn.Close();
            //計算總頁數、當前頁數

            totalPage = (nMax / pageSize);    //計算出總頁數

            if ((nMax % pageSize) > 0) totalPage++;

            //如果最大頁數大於0,查詢第一頁數據。爲1,則當前頁要取的數據條數爲總記錄數,否則爲頁面行數
            if (totalPage > 0)
            {
                //計算當前頁數,如果記錄的臨時當前頁數大於零
                if (currentPage > totalPage)//臨時當前頁大於總頁數
                {
                    currentPage = totalPage;
                }

                //如果當前頁等於總頁數
                if (totalPage == currentPage)
                {
                    pageCount = nMax - (currentPage - 1) * pageSize;
                }
                else
                {
                    pageCount = pageSize; ;
                }

                //查詢數據
                getSelectRecord();
                //更改狀態欄的頁碼信息
                this.label1.Text = currentPage.ToString() + " / " + totalPage.ToString();
            }
            else
            {
                //更改狀態欄的頁碼信息
                this.label1.Text = "0 / 0";
            }
        }

        //查詢數據庫,獲取並顯示要查的指定數據
        private void getSelectRecord()
        {
            //查詢數據
            _sql = "select * from PersonId limit " + (currentPage-1)*pageSize + "," + pageCount;
            cmd.Connection = conn;
            cmd.CommandText = _sql;
            dataAdapter = new SQLiteDataAdapter(cmd);
            dataAdapter.Fill(dataSet, "PersonId");
            dataTable = dataSet.Tables["PersonId"];

            //數據綁定顯示            
            this.bindingSource1.DataSource = dataTable;
            this.dataGrid1.DataSource = bindingSource1;
        }

        //刪除某一條記錄
        private void menuItem1_Click_1(object sender, EventArgs e)
        {
            selectRow = this.dataGrid1.CurrentRowIndex;
            if (selectRow >= 0)
            {
                DialogResult dialogResult = MessageBox.Show("確認要刪除該條記錄嗎?", "刪除確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dialogResult == DialogResult.OK)
                {
                    //刪除數據庫記錄
                    object[] datas = dataTable.Rows[selectRow].ItemArray;
                    int delR = this.deleteRecord(datas[0].ToString());//刪除數據庫記錄,以rowId爲索引
                    if (delR == 1)//如果刪除成功,返回1,更新dataTable裏的數據
                    {
                        dataTable.Rows[selectRow].Delete();
                        dataTable.AcceptChanges();

                        //再次初始化數據集合
                        InitializeDataSource();
                    }
                    else
                    {
                        MessageBox.Show("記錄刪除失敗!");
                    }
                }
            }
            else
            {
                MessageBox.Show("當前無被選中記錄!");
            }
        }

        //上一頁
        private void bt_previous_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
            {
                if (currentPage > 1)
                {
                    currentPage--;
                    InitializeDataSource();
                }
            }
        }

        //下一頁
        private void bt_next_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
            {
                if (currentPage < totalPage)
                {
                    currentPage++;
                    InitializeDataSource();
                }
            }
        }

        //執行刪除數據記錄操作
        private int deleteRecord(string id)
        {
            string delStr = "";
            //如果ID不爲空,則刪除指定ID記錄
            if (id != null)
            {
                delStr = "delete from PersonId where rowId=" + id;
            }
            else//如果ID爲空,則清空所有記錄
            {
                delStr = "delete from PersonId";
            }
            //建立數據庫連接
            conn.Open();
            cmd.CommandText = delStr;
            cmd.Connection = conn;
            int delResult = cmd.ExecuteNonQuery();
            conn.Close();
            return delResult;
        }

        //清空,刪除所有記錄
        private void menuItem2_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
            {
                DialogResult dialogResult = MessageBox.Show("確認要刪除所有記錄嗎?", "刪除確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dialogResult == DialogResult.OK)
                {

                    this.deleteRecord(null);//刪除數據庫所有記錄
                    dataTable.Clear();
                    dataTable.AcceptChanges();
                    InitializeDataSource();
                }
            }
            else
            {
                MessageBox.Show("當前無記錄可刪除!");
            }
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            selectRow = this.dataGrid1.CurrentRowIndex;
            if (selectRow >= 0)
            {
                //獲取數據記錄信息並顯示
                object[] datas = dataTable.Rows[selectRow].ItemArray;
                form4.initData(datas);
                form4.Show();
            } 
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            InitializeDataSource();
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章