1. 程式人生 > >LINQ管理SQL SERVER

LINQ管理SQL SERVER

1.新增資料
使用LINQ向SQL SERVER中新增資料,主要用到InsertOnSubmit方法和SubmitChanges方法
InsertOnSubmit方法用來將處於pending insert狀態的實體新增到SQL資料表中
SubmitChanges用來記錄要插入,更新和刪除的物件,並執行相應命令實現對資料庫的更改.
例:建立Windows應用程式,實現向資料庫中新增資料
在這裡插入圖片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LINQ_to_SQL
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        string str = @"Server=;database=;uid=;pwd=";
        linqtosqlDataContext linq;
        public void dgv()
        {
            SqlConnection conn = new SqlConnection(str);
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter("select*from information", conn);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            dgv();
        }
      
        private void button1_Click(object sender, EventArgs e)
        {
         int i = Convert.ToInt32(textBox1.Text);
            int j = Convert.ToInt32(textBox3.Text);
        
            linq = new linqtosqlDataContext(str);
            information info = new information();//建立information類物件
        info.ID = i;
            info.NAME = textBox2.Text;
            info.SEX = textBox4.Text;
            info.TEL = textBox5.Text;
            info.AGE = j;
            linq.information.InsertOnSubmit(info);
            linq.SubmitChanges();
            MessageBox.Show("新增成功");
            dgv();

        }
    }
}

注:若要ID列實現自增編號在資料庫設計時的資料庫語句為
create table test111
(
mID int identity(1,1),
mName varchar(50),
mRemark varchar(30)
)
其中:itentity(a,b)為自動編號項, 以a開始,每次新增一條資料,該值增加b
2.修改,刪除資料
修改資料時需要 用到SubmitChanges方法,刪除資料用到DeleteAllOnSubmit方法
建立windows應用程式,設計如圖介面
在這裡插入圖片描述
在dgv控制元件中新增一個contextMenuStrip用來作為刪除快捷選單
實現程式碼如下

namespace LINQ_to_SQL
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
        string str = @"Server=;database=;uid=;pwd=";
        linqtosqlDataContext linq;
        string strid = "";
        private void Form3_Load(object sender, EventArgs e)
        {
            dgv();
        }
//當在DGV中選中某條記錄時,根據選中記錄的員工編號查詢其詳細資訊,並顯示在相應的文字框中程式碼如下:
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
             strid = Convert.ToString(dataGridView1[0, e.RowIndex].Value).Trim();//獲取選中的編號
            linq = new linqtosqlDataContext(str);
            textBox1.Text = Convert.ToString(dataGridView1[0, e.RowIndex].Value).Trim();//根據選中編號獲取詳細資訊,並重新生成一個表
            int i = Convert.ToInt32(textBox1.Text);
            var result = from info in linq.information
                         where info.ID == i
                         select new
                         {
                             id = info.ID,
                             name = info.NAME,
                             age = info.AGE,
                             sex = info.SEX,
                             tel = info.TEL

                         };
            foreach(var item in result)
            {
                textBox2.Text = item.name;
                textBox3.Text = item.age.ToString();
                textBox4.Text = item.sex;
                textBox5.Text = item.tel.ToString();
            }
                
                }
//修改資訊
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("選擇要修改的編號");
                return;
            }
            int i = Convert.ToInt32(textBox1.Text);
            linq = new linqtosqlDataContext(str);//建立linq連線物件
            var result = from info in linq.information
                         where info.ID == i
                         select info;
            foreach(information info in result)
            {
                int a = Convert.ToInt32(textBox3.Text);
                info.NAME = textBox2.Text;
                info.AGE = a;
                info.SEX = textBox4.Text;
                info.TEL = textBox5.Text.ToString();
                linq.SubmitChanges();
            }
            MessageBox.Show("資訊修改成功");
            dgv();

                      
        }
        #region
        //獲取資料庫資訊,顯示在dgv中
        public void dgv()
        {
            linq = new linqtosqlDataContext(str);
            var result = from employee in linq.information
                         select new
                         {
                             編號 = employee.ID,
                             姓名 = employee.NAME,
                             性別 = employee.SEX,
                             電話 = employee.TEL
                         };
            dataGridView1.DataSource = result;
                       

        }
        #endregion
//刪除所選資料
        private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (strid == "")
            {
                MessageBox.Show("選擇要刪除的記錄");
                return;
            }
            int i = Convert.ToInt32(strid);
            linq = new linqtosqlDataContext(str);
            var result = from info in linq.information
                         where info.ID == i
                         select info;
            linq.information.DeleteAllOnSubmit(result);//刪除選中資訊
            linq.SubmitChanges();
            MessageBox.Show("刪除成功");
            dgv();
        }
    }
}