此處將資料從資料庫得出後顯在DataGridView上顯示。然後變更資料。變更資料的方法在按鈕事件中。
資料顯示方法不用多說。
更新時主要用到SqlCommandBuilder類和SqlDataAdapter.Update()方法。
SqlCommandBuilder對象負責產生用於更新資料庫的SQL語句,不必自己建立這些語句。
UpDate方法自動遍曆DataTable中的行,以找出需要對資料庫作出變動。Rows集合中每個DataRow對象都具有屬性RowState,可以跟蹤此行是否已刪除、添加、修改,還是未作變動。所作的任何變化都會反映到資料庫中。
例:更新表中內容:
using System.Data.SqlClient;
namespace UpdatingData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnUpdate.Click += new EventHandler(btnUpdate_Click);
UpdateData();
}
string sConnection = "Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123";
DataSet dsSet = new DataSet();
SqlDataAdapter sdaAdapter = null;
SqlCommandBuilder scbBuilder = null;
private void UpdateData()
{
//建立Connection
SqlConnection scConnection = new SqlConnection(sConnection);
//建立Command
SqlCommand scCommand = scConnection.CreateCommand();
scCommand.CommandText = "select customerID,contactName from customers";
//建立Adapter
sdaAdapter = new SqlDataAdapter(scCommand);
//該對象負責產生用於更新資料庫的SQL語句,不必自己建立這些語句
scbBuilder = new SqlCommandBuilder(sdaAdapter);
//得到資料
sdaAdapter.Fill(dsSet, "customers");
dgvView.DataSource = dsSet.Tables["customers"];
}
void btnUpdate_Click(object sender, EventArgs e)
{
//設定值
dsSet.Tables["customers"].Rows[3]["contactName"] = "Thomas Hardy";
//更新資料(UpDate方法自動遍曆DataTable中的行,以找出需要對資料庫作出變動)
//Rows集合中每個DataRow對象都具有屬性RowState,可以跟蹤此行是否已刪除、添加、修改,還是未作變動。所作的任何變化都會反映到資料庫中。
sdaAdapter.Update(dsSet, "customers");
dgvView.DataSource = dsSet.Tables["customers"];
}
}
}
例:在表中增加行
using System.Data.SqlClient;
namespace AddingData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Click += new EventHandler(btnAdd_Click);
UpdateData();
}
string sConnection = "Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123";
DataSet dsSet = new DataSet();
SqlDataAdapter sdaAdapter = null;
SqlCommandBuilder scbBuilder = null;
private void UpdateData()
{
//建立Connection
SqlConnection scConnection = new SqlConnection(sConnection);
//建立Command
SqlCommand scCommand = scConnection.CreateCommand();
scCommand.CommandText = "select customerID,companyName from customers";
//建立Adapter
sdaAdapter = new SqlDataAdapter(scCommand);
//該對象負責產生用於更新資料庫的SQL語句,不必自己建立這些語句
scbBuilder = new SqlCommandBuilder(sdaAdapter);
//得到資料
sdaAdapter.Fill(dsSet, "customers");
dgvView.DataSource = dsSet.Tables["customers"];
}
void btnAdd_Click(object sender, EventArgs e)
{
AddRow();
}
private void AddRow()
{
//建立表中的行
DataRow drRow = dsSet.Tables["customers"].NewRow();
drRow["customerID"] = "ZaCzi";
drRow["companyName"] = "Zachary Zithers Ltd.";
//增加行
dsSet.Tables["customers"].Rows.Add(drRow);
//更新表
sdaAdapter.Update(dsSet, "customers");
//顯示
dgvView.DataSource = dsSet.Tables["customers"];
}
}
}