Sqlcommandbuilder là gì

THÊM DỮ LIỆU

 using System;
using System.Data;
using System.Data.SqlClient;

class Class1{
public static void Main() {
SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");

SqlDataAdapter thisAdapter = new SqlDataAdapter( 
"SELECT ID, FirstName FROM Employee", thisConnection);

SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

DataSet thisDataSet = new DataSet();

thisAdapter.Fill(thisDataSet, "Employee");

Console.WriteLine("# rows before change: {0}",thisDataSet.Tables["Employee"].Rows.Count);

DataRow thisRow = thisDataSet.Tables["Employee"].NewRow();
thisRow["ID"] = "123";
thisRow["FirstName"] = "Ltd";
thisDataSet.Tables["Employee"].Rows.Add(thisRow);

Console.WriteLine("# rows after change: {0}", thisDataSet.Tables["Employee"].Rows.Count);

thisAdapter.Update(thisDataSet, "Employee");
}
}


Xóa dữ liệu

 using System;
using System.Data;
using System.Data.SqlClient;

class PropagateDeletes {
static void Main() {
string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

string qry = @"select * from employee ";

string del = @"delete from employee where id = @id";

SqlConnection conn = new SqlConnection(connString);

try {
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(qry, conn);

DataSet ds = new DataSet();   
da.Fill(ds, "employee");
DataTable dt = ds.Tables["employee"];

SqlCommand cmd = new SqlCommand(del, conn);
cmd.Parameters.Add("@id",SqlDbType.Int, 4, "id");
string filt = @"firstname = 'o' and lastname = 'B'";

foreach (DataRow row in dt.Select(filt)) {
row.Delete();
}
da.DeleteCommand = cmd;
da.Update(ds, "employee");

foreach (DataRow row in dt.Rows) {
Console.WriteLine(
"{0} {1}",
row["firstname"].ToString().PadRight(15),
row["lastname"].ToString().PadLeft(25));
}
} catch(Exception e) {
Console.WriteLine("Error: " + e);
} finally {
conn.Close();
}
}  
}


Sửa dữ liệu:

 using System;
using System.Data;
using System.Data.SqlClient;

class Class1{
static void Main(string[] args){
SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT ID, FirstName FROM Employee", thisConnection);

SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

DataSet thisDataSet = new DataSet();

thisAdapter.Fill(thisDataSet, "Employee");

Console.WriteLine("name before change: {0}", thisDataSet.Tables["Employee"].Rows[9]["FirstName"]);

thisDataSet.Tables["Employee"].Rows[1]["FirstName"] = "Inc";

thisAdapter.Update(thisDataSet, "Employee");

Console.WriteLine("name after change: {0}", thisDataSet.Tables["Employee"].Rows[9]["FirstName"]);


}
}

Code không có gì khó hiểu, mọi người ráng tham khảo nhé, có gì không hiểu thì hỏi mình (nhớ post vào mục HỎI - ĐÁP nhá)

Nếu như SqlDataReader đọc từng hàng dữ liệu thì SqlDataAdapter đọc toàn bộ dữ liệu một lần. Dữ liệu nhận được sẽ được lưu trữ trong DataTable hay DataSet. DataTable giống như các bảng, DataSet giống như một sơ sở dữ liệu. Một DataSet có thể chứa nhiều DataTable.

Đoạn mã sau dùng đối tượng SqlDataAdapter để đọc dữ liệu từ bảng Khoa của cơ sở dữ liệu QuanLySinhVien và lưu trữ dữ liệu này trong một đối tượng DataTable bằng phương thức Fill:

try

{

  DataTable khoa = new DataTable();

  string connectionString = ConfigurationManager.ConnectionStrings["QLSV"].ConnectionString;

  using (SqlConnection connection = new SqlConnection(connectionString))

  using (SqlCommand command = new SqlCommand("SELECT MaKhoa, TenKhoa FROM Khoa;",

  connection))

  {

    using (SqlDataAdapter adapter = new SqlDataAdapter(command))

    {

      adapter.Fill(khoa);

    }

  }

  Console.WriteLine("Du lieu tu bang Khoa:");

  foreach (DataRow r in khoa.Rows)

  {

   string sFormat = String.Format("Ma Khoa:{0} Ten Khoa: {1}", 
                    
                    r["MaKhoa"], r["TenKhoa"]);

   Console.WriteLine(sFormat);

  }

}

catch (Exception ex)

{

  Console.WriteLine("Loi khi mo  ket noi:" + ex.Message);

}

Thêm hàng mới đến DataTable và cập nhật đến cơ sở dữ liệu:

try

{

  DataTable khoa = new DataTable();

  string connectionString = ConfigurationManager.ConnectionStrings["QLSV"].ConnectionString;

  using (SqlConnection connection = new SqlConnection(connectionString))

  using (SqlCommand command = new SqlCommand("SELECT*FROM Khoa", connection))

  using (SqlDataAdapter adapter = new SqlDataAdapter(command))

  using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter))

  {

   adapter.FillSchema(khoa, SchemaType.Source);

   adapter.Fill(khoa);

   DataRow khoamoi = khoa.NewRow();

   khoamoi["MaKhoa"] = "MH09";

   khoamoi["TenKhoa"] = "Cong nghe Sinh Hoc";

   khoa.Rows.Add(khoamoi);

   adapter.Update(khoa);

  }

  Console.WriteLine("Them du lieu thanh cong!");

}

catch (Exception ex)

{

  Console.WriteLine("Loi khi mo  ket noi:" + ex.Message);

}

Thay đổi nội dung của một hàng đã tồn tại trong DataTable và cập nhật đến cơ sở dữ liệu:

try

{

  DataTable khoa = new DataTable();

  string connectionString = ConfigurationManager.ConnectionStrings["QLSV"].ConnectionString;

  using (SqlConnection connection = new SqlConnection(connectionString))

  using (SqlCommand command = new SqlCommand("SELECT*FROM Khoa", connection))

  using (SqlDataAdapter adapter = new SqlDataAdapter(command))

  using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter))

  {

    adapter.FillSchema(khoa, SchemaType.Source);

    adapter.Fill(khoa);

    DataRow[] dt = khoa.Select("MaKhoa = 'KH07'");

    dt[0]["TenKhoa"] = "Cat got kim loai";

    adapter.Update(dt);

  }

   Console.WriteLine("Cap nhat du lieu thanh cong!");

}

catch (Exception ex)

{

   Console.WriteLine("Loi khi mo  ket noi:" + ex.Message);

}

Xoá một hàng trong DataTable và cập nhật đến cơ sở dữ liệu:

try

{

  DataTable khoa = new DataTable();

  string connectionString = ConfigurationManager.ConnectionStrings["QLSV"].ConnectionString;

  using (SqlConnection connection = new SqlConnection(connectionString))

  using (SqlCommand command = new SqlCommand("SELECT*FROM Khoa", connection))

  using (SqlDataAdapter adapter = new SqlDataAdapter(command))

  using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter))

  {

    adapter.FillSchema(khoa, SchemaType.Source);

    adapter.Fill(khoa);

    DataRow[] dt = khoa.Select("MaKhoa = 'MH09'");

    dt[0].Delete();

    adapter.Update(dt);

  }

  Console.WriteLine("Xoa du lieu thanh cong!");

}

catch (Exception ex)

{

 Console.WriteLine("Loi khi mo  ket noi:" + ex.Message);

}

Học C# và WPF >

Chia sẻ:

  • Tweet
  • Email

Thích bài này:

Thích Đang tải...