此處將資料從數據庫得出后顯在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"];
}
}
}
新聞熱點
疑難解答