這里主要是復習DataSet等數據或ADO.NET方面的知識。下面是一個(gè)簡(jiǎn)單的數據存儲(在DataGridView上增加一行然后并存儲到數據庫的過(guò)程):
private void button1_Click(object sender, EventArgs e)
{
//插入一行內容
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=數據庫名;User ID=sa;pwd=***");
con.Open();
SqlDataAdapter thisAdapter = new SqlDataAdapter("select itemId,productId,listPrice,unitCost,supplier,status,name,image from Item", con);
SqlCommandBuilder scb = new SqlCommandBuilder(thisAdapter);
DataSet ds = new DataSet();
thisAdapter.Fill(ds, "Item");
try
{
if (txtItemId.Text != "" && txtPicture.Text != "" && txtProductCount.Text != "" && txtProductId.Text != "" && txtProductName.Text != "" && txtProductPrice.Text != "" && txtYouhuiPrice.Text != "")
{
//TODO:判斷txtitemid里的內容已經(jīng)存在數據庫(寫(xiě)個(gè)bool方法,然后再次判斷調用即可)
DataRow newRow = ds.Tables["Item"].NewRow();
newRow["itemId"] = this.txtItemId.Text;
newRow["productId"] = this.txtProductId.Text;
newRow["listPrice"] = this.txtProductPrice.Text;
newRow["unitCost"] = this.txtYouhuiPrice.Text;
newRow["supplier"] = this.txtProductCount.Text;
newRow["status"] = this.comboSellMode.Text;
newRow["name"] = this.txtProductName.Text;
newRow["image"] = this.txtPicture.Text;
ds.Tables["Item"].Rows.Add(newRow);
thisAdapter.Update(ds, "Item");
}
//更新datagridview表格
//此處因為是綁定數據,不能用此句代碼直接插入一行數據
//dataGridView1.Rows.Add(new object[] { txtItemId.Text, txtProductId.Text, txtProductPrice.Text, txtYouhuiPrice.Text, txtProductCount.Text, comboSellMode.Text, txtProductName.Text, txtPicture.Text });//{}是對應列的值
else
{
MessageBox.Show("請將信息填寫(xiě)完整,并符合規則!", "Message to you:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("請檢查信息輸入格式!" + ex.Message, "Message to you,", MessageBoxButtons.OK, MessageBoxIcon.Error);
//這里有個(gè)bug,沒(méi)有實(shí)現表的同步更新
}
}
一般關(guān)于使用DataSet的用法基本上都是一個(gè)模式,或者說(shuō)數據連接這一塊都是一個(gè)模式。
1. 首先就是SqlConnection 來(lái)new出來(lái)一個(gè)連接數據庫的字符串;
2. 接著(zhù)用DataAdapter對數據進(jìn)行許多不同種類(lèi)的操作,包括查詢(xún)、更新和刪除。它比DataReader對象更加通用一些;
3.然后并沒(méi)有編寫(xiě)SQL語(yǔ)句來(lái)進(jìn)行更新,而是創(chuàng )建了更簡(jiǎn)單實(shí)用的CommandBuilder對象,它可以為我們創(chuàng )建正確的SQL語(yǔ)句,然后并將其自動(dòng)與DataAdaper相關(guān)聯(lián);
4.接下來(lái)就到了ado.net中重要的DataSet對象了,所有的復雜操作都會(huì )使用到它。它包含一組相關(guān)的DataTable對象,代表要使用的數據庫表。每一個(gè)DataTable對象都有子DataRow和DataColumn對象,分別代表數據庫表的行列。通過(guò)這些對象就可以獲得表的所有元素;
5.然后就是DataAdapter的填充方法 :thisAdapter.Fill(ds, "Item");
6.最后要注意的是:數據庫連接打開(kāi)后,最后一定要關(guān)閉;對數據表操作后,一定要執行UpDate()方法,才能將修改保存到數據庫;它隸屬于DataAdapter。
上面六步基本就是各種套路的東西了,如果有對數據的操作,就可以把這些操作的語(yǔ)句放在填充之后,也就是Fill()方法之后,因為這些的更改只是停留在內存,需要最后執行DataAdapter的UpDate()方法才能最終得以更新到數據庫中。
當這樣的操作比較多的時(shí)候,就會(huì )發(fā)現很多方法的代碼都是重復的,也就是上面那些套路。這個(gè)時(shí)候,我們就要用到面向對象了,也就是把這些相同的東西提取出來(lái)寫(xiě)成一個(gè)方法讓大家共享,這就是一個(gè)面向對象或是不斷重載等進(jìn)行代碼簡(jiǎn)化的過(guò)程,這就是真正嚴謹的開(kāi)發(fā)的開(kāi)始了吧。
本文來(lái)自CSDN博客,轉載請標明出處:
http://blog.csdn.net/loundar/archive/2009/08/03/4404919.aspx