C#Sqlite增刪改查


            說到使用數據庫的話,無非也就是對數據的增加,刪除和修改以及查詢。前文已經

創建好了程序,現在我們就可以來具體實現Sqlite的數據操作,增刪改查。

            第一步,創建連接字符串來連接數據庫:

            private void lianjie(){}//重新寫個方法,將代碼寫在里面,然后放到窗體加載事件中,

因為是窗體起始要顯示的數據。增刪改查則要寫在按鈕的點擊事件里面。

            string Sqlite= @"C:/Users/Administrator/Desktop/SQLlite/yy.db";數據表的路徑
            SQLiteConnection con = new SQLiteConnection("data source="+Sqlite);
            con.Open();

            第二步,創建命令對象執行SQL語句:

            

            SQLiteCommand cmd = new SQLiteCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;

            if (textBox6.Text!="")
            {
                cmd.CommandText = "select * from User where Name like '%"+textBox6.Text+"%'";//查詢輸入
            }
            else
            {
                cmd.CommandText = "select * from User";//查詢所有
            }

         第三步,將數據綁定到Bindingsource。

            //數據源和數據集的交換
            SQLiteDataAdapter da = new SQLiteDataAdapter();
            DataSet dt = new DataSet();
            da.SelectCommand = cmd;
            da.Fill(dt);

            //將數據綁定bindingsource
            bindingSource1.DataSource = dt.Tables[0];

            //將bindingsource中的值賦給GridView
            dataGridView1.DataSource = bindingSource1;

            //關閉連接
            con.Close();

            第四步,文本框獲取值。Clear()清除值。(這個寫到窗體加載中)

            this.textBox1.Clear();
            this.textBox1.DataBindings.Add("Text", bindingSource1, "Id");
            this.textBox2.Clear();
            this.textBox2.DataBindings.Add("Text",bindingSource1,"Name");
            this.textBox3.Clear();
            this.textBox3.DataBindings.Add("Text", bindingSource1, "Sex");
            this.textBox4.Clear();
            this.textBox4.DataBindings.Add("Text", bindingSource1, "Class");
            this.textBox5.Clear();
            this.textBox5.DataBindings.Add("Text",bindingSource1,"Number");

 

           第五步,增刪改,寫在不同的點擊事件中。同樣的創建連接,創建命令。(SQL語句不同)

            string sqlite = @"C:/Users/Administrator/Desktop/SQLlite/yy.db";數據表的路徑
            SQLiteConnection con = new SQLiteConnection("data source=" + sqlite);
            con.Open();
            string sql = "delete from User where Number='" + textBox5.Text + "'";
            SQLiteCommand com = new SQLiteCommand(sql,con);
            com.Connection = con;
            int rows = com.ExecuteNonQuery();

            MessageBox.Show("刪除成功!"+rows+"");
            con.Close();關閉
            lianjie();  //刷新數據調用查詢方法

          最后,完成!😊


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM