資料庫中有些表格的某些欄位是設成Identity(種子,會自動累加),那個數字是由資料庫在進行insert時給的,也就是說要存了,才知道數值是存多少,然後更改User端畫面上那個欄位的值(如果畫面上放了那個欄位的話)

下列預存程序和程式碼範例示範如何從 Microsoft SQL Server 資料表,將自動遞增的識別項值對應回加入 DataSet 資料表的資料列中與識別 (Identity) 值對應的資料行。預存程序則用來將新資料列插入 Northwind 資料庫的 Categories 資料表,並將 Transact-SQL SCOPE_IDENTITY() 傳回的 Identity 值當成輸出參數。

請在資料庫上建立一個預儲程序(store proc),如下:

CREATE PROCEDURE InsertCategory@CategoryName nchar(15),@Identity int OUTASINSERT INTO Categories (CategoryName) VALUES(@CategoryName)SET @Identity = SCOPE_IDENTITY()

程式碼如下:
//textBox1.Text="Data Source=YAI;Initial Catalog=Northwind;User ID=sa";
            SqlConnection connection = new SqlConnection(textBox1.Text);

// Assumes that connection is a valid SqlConnection object.
            SqlDataAdapter adapter = new SqlDataAdapter(
              "SELECT CategoryID, CategoryName FROM dbo.Categories", connection);
           
            adapter.InsertCommand = new SqlCommand("InsertCategory", connection);
            adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
            
            adapter.InsertCommand.Parameters.Add(
              "@CategoryName", SqlDbType.NChar, 15, "CategoryName");

            SqlParameter parameter = adapter.InsertCommand.Parameters.Add(
              "@Identity", SqlDbType.Int, 0, "CategoryID");
            parameter.Direction = ParameterDirection.Output;

            //以上白話大概意思就是,把@CategoryName跟CategoryName綁在一起,@Identity跟CategoryID綁在一起,update時會去執行InsertCategory這個proc,會把Categories.CategoryName->@CategoryName,而Categoryies.CategoryID則會接收回傳值

            connection.Open();//不打這行也沒關係,因為進行Fill時,SqlDataAdapter會自己去open它

            DataSet categories = new DataSet();
           
            adapter.Fill(categories, "Categories");
            dataGridView1.DataSource = categories.Tables["Categories"];//畫面上可以很清楚看到,那個Identity會自動在DB存入後,回傳回來

            DataRow newRow = categories.Tables["Categories"].NewRow();//新增一筆record
            newRow["CategoryName"] = "New Category";//給值
            categories.Tables["Categories"].Rows.Add(newRow);

            adapter.Update(categories, "Categories");
           
            connection.Close();//沒事就關起來吧,反正資料都抓到categories這個dataSet了



arrow
arrow
    全站熱搜
    創作者介紹
    創作者 pagichang 的頭像
    pagichang

    pagichang

    pagichang 發表在 痞客邦 留言(0) 人氣()