You are on page 1of 20

1-Ngh Nghip -Teacher : gio vin -Rector : hiu trng -Professon :Gio s H -Student :Sinh vin -Doctor :bc

s -Nurse (ns) : y t -Dentist : nha s -Worker : cng nhn -Farmer :nng dn -Gandence :ngi lm vn -Janitor (dzennitor) ngi gc cng -Housekeeper :qun gia -officer :nhn vin cng chc -Accountant :k ton -Receptionist (rsptionnt) :tip tn -Secretary(scktery) :th k -Manager :qun l/gim c -Pilot : phi cng -Waiter :ngi hu bn -Cook :u bp -Chief cook : bp trng -Master :thuyn trng -Sailor :thy th -Businessman : thng nhn -Foreman :qun c/c cng -Engineer :k s -Mechanic :th my -Architect :kin trc s -Builder : ch thu -painter : ha s -artist : ngh s -musician : nhc s -singer : ca s -footballer : cu th -actor : nam din vin -actress : n dv -pianist : ngh si piano -detective : thm t -judge : quan ta(trach d) -defendant : b co -witness : nhn chng -police : cng an -suspect : nghi phm -thief : trm -barber : th co ,th ct tc

-photographer : th chp nh -locksmith :th cha kha -electrician :th in -watchmaker :th ng h -washerwoman : th git -bricklayer :th n -diver : th ln -goldsmith : th kim hon -blacksmith : th rn -plumber : thj sa ng nc -carpenter : th mc -baker : th lm bnh -painter : th sn -turner : th in 1-Tng Data Transfer Object (DTO ) -Khai bo bin -Gn thuc tnh -C th khi to gi tr 2-Data Access Layer (DAL) -Khai bo i tng di n DTO -Public DTO -Khi to DTO -Khai bo bin Li v Public -Thc thi cu lnh : thm ,xa Sa... 3-Business Layer (BL) -Khai bo DTO , DAL -Public DTO -Khi to DTO ,DAL -Khai bo Li v Public -To hm gi li thuc tnh DAL : thm ,xa ,sa... -Gn DTO thuc lp DAL = DTO ca DL mi DAL.DTO=DTO 4-Giao din -Khai bo DTO , BL -Gn thuc tnh t giao din cho thuc tnh trong DTO -BL.DTO=DT

INSERT vo CSDL
-To chui kt ni ti CSDL ( string chui kt ni = @"Data Source=DUNG-PC\SQLEXPRESS;Initial ) -Khi to kt ni ( SqlConnection bien = new SqlConnection(chui kt ni); )
Catalog=tn CSDL;Integrated Security=True"

-Kim tra kt ni m cha if (bin (SqlConnection) .State == ConnectionState.Closed) if (!this.Connect())

return false; -To cu Insert string chui insert="insert into CHUC_VU(TenCV) Values('" + Dto1.TenCV + "')"; + Nu kiu s th ch: +"ten.ToString()"+ + Nu kiu chui th: '"+ten+"' -Khi to bin SqlCommand cha cu truy vn v chui kt ni SqlCommand command = new SqlCommand(cu lnh Insert, bin SqlConnection ) -Lu command.ExecuteNonQuery() kt qu lu tr v kiu boolb: 0 or 1 Select CSDL C1 dung DataTable; SqlConnection conect = new SqlConnection(@"Data Source=VANDUNGPC\sqlexpress;Initial Catalog=aa;Integrated Security=True"); conect.Open(); string str = "select * from vidu"; //ta SqlDataAdapter ly DL ln ch SqlDataAdapter da=new SqlDataAdapter (str,conect); DataSet ds = new DataSet(); //khi to DataTable cha DL do SqlDAtaAdapter ly v DataTable datatable = new DataTable(); // DL vo DataTable da.Fill(datatable); // DL ra cng c dataGridView1.DataSource=datatable; C2 Dung DataSet SqlConnection conect = new SqlConnection(@"Data Source=VANDUNGPC\sqlexpress;Initial Catalog=aa;Integrated Security=True"); conect.Open(); string str = "select * from vidu"; SqlDataAdapter da=new SqlDataAdapter (str,conect); DataSet ds = new DataSet(); DataTable datatable = new DataTable(); da.Fill(ds,"tentable1"); datatable = ds.Tables["tentable1"]; dataGridView1.DataSource=datatable;

Lm vic vi DataSet v DataAdapter


Xem mc lc bi trc bn bit cch x l v hin kt qu ra mn hnh dng Data Reader. Ch rng : nu ch mun xem thng tin th dng Data Reader. Bi ny hng dn s dng DataSet x l kt qu kt hp vi DataAdapter. Khng ging vi DataReader, to ra cc i tng dng interface System.DataIDataReader, th DataSet l mt thnh phn c trng ca ADO.NET c s dng bi tt c cc nh cung cp d liu (data provider). Dataset c th hon ton c lp v s dng

khi kt ni hoc ngt kt ni khi ngun. Mc ch c bn ca DataSet l cung cp x l xem xt d liu lu tr trong mt memory cache. Nu nh mt DataSet khng kt ni ti c s d liu th lm sao m x l d liu v save li vo database ? y l l do m DataAdapter ra i. Hy ngh DataAdapter chnh l mt chic cu ni gia DataSet v Data Source. Nu khng c mt DataAdapter no th DataSet khng th truy cp bt c DataSource no. DataAdapter m bo vic kt ni v truyn thng tin cho DataSet. Tm hiu v ObjectModel u tin th mnh a ra mt s so snh gia DataSet v DataReader nh, cc bn trnh hay hi nhiu v vic : Lc no th xi DataSet v lc no th xi DataReader, ging v khc nhau nh th no ? So snh DataSet v DataReader Nu bn n gin chi mun ly d liu v trnh by n ra thi th dng DataReader. c bit trng hp m bn c vi mt s lng ln d liu, v nh l vng lp ti hng triu dng kt qu d liu, bn mun tc c nhanh v trnh by nhanh th DataReader c s dng cho mc ch ny, NHANH v TIN LI, cho vic C d liu. Nu bn mun chnh s d liu ri update thng tin d liu li database th bn s dng DataSet. DataAdapter lp y (fill) d liu vo DataSet bng cch s dng mt DataReader, thm vo resource cn c lu tr vo s dng khi ngt kt ni. V vy vic s dng DataSet tn nhiu ti nguyn hn DataReader rt nhiu, bn cn cn nhc y lc no s dng thnh phn no th tt, trnh lm dng qu. Nu nh bn mun c d liu v vit ra di dng XML, hoc export database schema, vit li db di dng XML,. th nn s dng DataReader. Gii thiu s qua v DataSet DataSet trong ADO.NET l mt bc pht trin ln trong vic pht trin ng dng c s d liu a h. Khi ly v chnh sa d liu, duy tr lin tc kt ni ti Data Source trong khi ch user yu cu th r rng l tn ti nguyn my rt nhiu. DataSet gip ch y rt ln. V DataSet cho php lu tr d liu v chnh sa ti local cache, hay gi l offline mode. C th xem xt v x l thng tin trong khi ngt kt ni. Sau khi chnh sa v xem xong th to mt kt ni v update d liu t local vo Data Source. D liu trong DataSet c lu tr di dng mt Collection cc Tables v bn cn phi x l thng qua cc lp DataTable -> DataRow v DataColumn. Bng di y l kin trc DataSet.

Gii thiu v DataAdapter Bn ch cn tng tng rng : bn c mt ci b nc (DataSource) , mt ci my bm (DataAdapter) v mt ci thng ng nc (DataSet). Th khi ly nc dng ci bm ly nc t b, kim tra v lc nc sau li dng ci bm ht li v ci b

nc. chnh l vai tr ca ci bm v DataAdapter tng t nh vy. ^_^! Gii thch hi chui. Tng quan 3 lp nh th ny :

C 4 cch to DataAdapter : [code=C#] // Cch 1 : n gin ch khai bo to i tng Adapter SqlDataAdapter da = new SqlDataAdapter(); // Cch 2 : Thit lp i tng SqlCommand SqlDataAdapter da = new SqlDataAdapter(cmd); // Cch 3 : Thit lp query v i tng SqlConnection SqlDataAdapter da = new SqlDataAdaoter(sql, conn); // Cch 4 : Thit lp query v mnh lnh thc thi SqlDataAdapter da = new SqlDataAdapter(sql, connString); Gii thiu v DataTable v thnh phn km Nm trong lp : System.Data.DataTable. C cu trc theo cu trc ca bng trong c s d liu gm cc hng v ct nn c 2 thnh phn km theo l : DataRow v DataColumn DataRow s l tp hp cc ct (record-set) DataColumn l tp hp cc hng cng mt c tnh. (Field) V d : Visual C# Code: La chn code | n/Hin code DataTable dt = new DataTable(); DataColumn col = dt.Columns[Contact]; // Ct Contact DataColumn col = dt.Columns[2]; DataRow row = dt.Rows[2]; Vy l gii thiu qua. By gi vo vn chnh no. Lm vic vi DataSet v DataAdapter To mt dataset : Visual C# Code: La chn code | n/Hin code DataSet ds = new DataSet(); DataSet ds = new DataSet(DataSet Name); Nu bn dng cch 1 th theo mc nh DataSet s c tn l NewDataSet, cch th 2 l bn t tn lun cho DataSet bn trong constructor. Hoc bn c th thay i tn ca DataSet bng thuc tnh DataSetName C nhiu cch x l vi DataSet nh S dng thng qua Adapter c t mt ti liu XML Cch th 2 lc khc nh. Lm c bn trc .

Th x l d liu bng mt v d : Visual C# Code: using System; using System.Data; using System.Data.SqlClient; La chn code | n/Hin code

namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string sql = @"SELECT productname, unitprice FROM products WHERE unitprice < 20"; // To connection SqlConnection conn = new SqlConnection(connString); try { // M kt ni conn.Open(); // To Adapter SqlDataAdapter da = new SqlDataAdapter(sql, conn); // To DataSet DataSet ds = new DataSet(); // Lp y kt qu vo DataSet da.Fill(ds, "products"); // To DataTable thu kt qu t bng DataTable dt = ds.Tables["products"]; // In kt qu ra Console foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) Console.WriteLine(row[col]); Console.WriteLine("".PadLeft(20, '=')); } } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } } }

Phn tch bi n gin trn nha. Sau khi m kt ni th ta to mt Adapter. Adapter ny cha thng tin v SQL query cn thc thi v mt i tng kt ni conn, sau to mt DataSet. Lc ny th DataSet cha c g. Sau lp y kt qu vo DataSet bng method Fill ca Adapter. T hiu thm rng : Adapter t ng thc thi cu lnh SQL , thu ly kt qu v gn ht vo DataSet. Khc vi DataReader cn c mt i tng SqlComnmand x l. Nu khi lp y kt qu vo DataSet m khng gn tn bng no th t ng trong DataSet tn ln lt tng bng l TableN vi bng u tin l Table, Table1,Table2TableN. Nu mt query c thc thi li nhiu ln th DataSet s cp nht thng tin tng bng vo trong . Ch trong Adapter trn nu thay bng cch to Adapter di y : Visual C# Code: La chn code | n/Hin code // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(sql, conn); Th kt qu thu c ging ht nhau, khng c g thay i. DataSet c th cha nhiu table v th khi x l Table no cn phi gn vo DataTable mt tn table c th. V cui cng dng DataColumn v DataRow x l DataTable . l cch extract d liu t DataSet. Phn loi v Sp xp trong DataSet Th v d di y : Visual C# Code: using System; using System.Data; using System.Data.SqlClient; La chn code | n/Hin code

namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string sql1 = @"SELECT * FROM customers "; string sql2 = @"SELECT * FROM products WHERE unitprice < 10 "; // Trn 2 query vo lm 1 string sql = sql1 + sql2; // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(sql, conn);

// To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "customers"); // Ly Data Table Collection DataTableCollection dtc = ds.Tables; // X l Table th nht Console.WriteLine("Result from Customers table : "); Console.WriteLine("Company Name".PadRight(20) + "Contact Name".PadLeft(23) + "\n"); // Thit lp Filter string filter = "country = 'Germany'"; // Thit lp Sort string sort = "companyname ASC"; // Hin th thng tin sort v filter foreach (DataRow row in dtc["customers"].Select(filter, sort)) { Console.WriteLine("{0}\t{1}", row["companyname"].ToString().PadRight(20), row["contactname"]); } // X l table th hai Console.WriteLine("\n---------------------------"); Console.WriteLine("Result from Products table"); Console.WriteLine("ProductName".PadRight(20) + "UnitPrice".PadLeft(21) + "\n"); // Hin th thng tin foreach (DataRow row in dtc[1].Rows) { Console.WriteLine("{0}\t{1}", row["productname"].ToString().PadRight(25), row["unitprice"]); } } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } } }

Hay nha Code ny y nhiu ch hi b phong y. Ch v cn thn nh. C gng nh nhng g t trnh by y n, hi rc ri mt cht y. ^_^! y x l 2 query sql1 v sql2 v chng c combine vo thnh 1 chui query sql. Adapter to ra thc thi 2 query ny. Vy th x l d liu th no ?..T t sau Sau lp y DataSet . Ch ci ny : Visual C# Code: La chn code | n/Hin code da.Fill(ds, customers); Nhc li no, 2 query trn l gi d liu t 2 bng : customers v products. y l lp y customers. Sau bn xem n ht code, khng h thy lp y thng products m vn in ra kt qu ca bng . Vy l sao ?. Ci th phi hi xem thng Fill lm vic th no. By gi bn th chn thm xung di cng trong khi try on code sau phn tch thng Fill Visual C# Code: La chn code | n/Hin code Console.WriteLine(ds.Tables[0]); Console.WriteLine(ds.Tables[1]); Ngha l in ra tn 2 bng trong DataSet. Bn s thy bng u tin l customers cn bng tip theo l customer1. Sau bn th foreach ly ht kt qu ca customers1 ra check th n chnh l kt qu thu c t query vo bng products. T c th suy lun ra cch lm vic ca Fill, u tin ta nh li l DataSet l lu tr mt lot cc Tables, khi Fill th Adapter s lp y tt c cc kt qu t cc Table vo DataSet. Vy th y sau khi query 2 tables th fill ln lt t customer n products vi cc Table sau customer b i tn thnh customerN ht. mun ly li tn ban u cho products th bn ch cn thay i tn i l c : Visual C# Code: La chn code | n/Hin code ds.Tables[1].TableName = products; Ch v query s c thc hin ln lt theo th t nn cc bng cng theo th t . By gi ngh ra mt ci hay nha.
Code:

da.Fill(ds, products); Thay vo trn th sao nh ? B li : Object Reference is not an instance of an object. L sao ? Tc l con tr vo i tng b NULL. Ti sao b NULL ? Th ny, theo th t query th customers trc products. Cho nn khi Fill cng theo th t . Ngha l phi fill bt u t Customers th con tr bt u i t Tables[0]. y ta b qua customers m vo lun products tc l Table[1], vy l khng c con tr ti Tables[0]. y b coi l mt Exception trong .NET. V th nu mun x l products trc th phi thay i th t query tc l : Sql = sql2 + sql1; Lc nu Fill nh trn th tn ca bng customers s b i thnh products1. Ok. Tip ! Lc ny DataSet cha nhiu Table v ta mun ly tt c th dng DataTableCollection thu lm tt c cc table trong DataSet. Hoc nu trnh cao th c ly ln lt theo index ds.Tables[int index] Bn tip c 2 string mi to l filter v sort

y l dng lc v sp xp d liu. Vy th nguyn tc lm th no ? n gin l bn dng b lc ca SQL, tc l to chui filter v sort theo syntax vit mt cu SQL y. C g xem bi vit u tin v SQL ca t nha. Trong cc table u c Method Select(string filter, string sort) lc d liu v sp xp. V d nh code trn t dng Select trong DataTableCollection. Nu trong DataSet th n l : ds.Tables[int index].Select(string filter, string sort); No, cha ht ci hay nha, tip. Hm n tienlbhoc c hi t th ny : T c c sch thy sch n dng v d, c Adapter v Connection m chng bao gi m (open) connection m chng trnh chy vn tt, th l th no nh? H h, vn ch t vit trn cng v ci my bm. Ci my bm thng vi ci b, by gi truyn nc v khng truyn nc l do ci my bm quyt nh. Cng vy y bn so snh 2 ci v d trn, mt ci m kt ni conn.Open() cn ci v d di th khng cn m. Nhc li method Fill(), method ny l mt c trng ca ADO.NET c cung cp truyn d liu cc DataSet v n T NG m kt ni khi gi n nu nh kt ni khng c m. V sau khi fill vo DataSet th li t ng ng kt ni. Mi vic y nm trong quyn kim sot ca ci Adapter ht. Bn c th t kim tra tnh trng kt ni State xc minh. S dng DataView DataView c dng xem thng tin d liu ca mt bng, ging nh SQL view, thm na n khng gi mt t d liu no. Vi d : S dng DataView Visual C# Code: La chn code | n/Hin code using System; using System.Data; using System.Data.SqlClient; namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string sql = @"SELECT contactname, country FROM customers "; // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(sql, conn); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "customers"); // Ly thng tin Table vo DataTable

DataTable dt = ds.Tables["customers"]; // To DataView DataView dv = new DataView(dt, "country = 'Germany'", "country", DataViewRowState.CurrentRows); // Hin th thng tin trong DataView foreach (DataRowView drv in dv) { for (int i = 0; i < dv.Table.Columns.Count; i++) { Console.Write(drv[i] + "\t"); } Console.WriteLine("");

} } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } }

} C th thy cch to mt DataView rt n gin. Vi 4 i s : a. tn Table b.filter c. sort d.DataViewRowState enum Gii thch mt cht v DataViewRowState Added : dng mi CurrentRows : cc dng hin ti, cha b thay i, mi v b sa i Deleted : dng xa ModifiedCurrent : gi tr sa ca dng sa ModifiedOriginal : gi tr trc khi sa ca dng sa None : Khng ly dng no OriginalRows : tt c dng ban u Unchanged : mt dng cha b sa i. Mi thao tc ca bn s c th lm thay i RowState, v vy nn ch v s dng cho hp l. Sa d liu trong DataSet Di y l minh ha sa i d liu trong DataSet. Nn nh l thay i trong dataset khng h nh hng g n Data Source. Mun thay i trong Data Source th phi to mt kt ni ti database v update d liu thay i ln thng qua DataSet v DataAdapter. Visual C# Code: La chn code | n/Hin code using System; using System.Data; using System.Data.SqlClient; namespace MSSQL_Server

";

class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string sql = @"SELECT * FROM employees WHERE country = 'UK' // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(sql, conn); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "employees"); // Ly thng tin Table vo DataTable DataTable dt = ds.Tables["employees"]; // Ct FirstName c th Null dt.Columns["FirstName"].AllowDBNull = true; // Thay i City ca Row u tin dt.Rows[0]["City"] = "Seoul"; // Thm mt dng mi nha DataRow newRow = dt.NewRow(); newRow["FirstName"] = "Pete"; newRow["LastName"] = "Houston"; newRow["TitleOfCourtesy"] = "Sir"; newRow["City"] = "Seoul"; newRow["Country"] = "South Korea"; dt.Rows.Add(newRow); // Add xong hin th thng tin t DataSet ra mn hnh

xem

// update cha foreach (DataRow row in dt.Rows) { Console.WriteLine("{0} {1} {2}", row["FirstName"].ToString().PadRight(10), row["LastName"].ToString().PadLeft(10), row["City"]); } } catch (Exception e) { // Bt li Console.WriteLine(e.Message); }

finally { // ng kt ni conn.Close(); } } } Run code trn xong, bn thy kt qu dng trn cng City l Seoul v di cng l mt dng mi, chnh l thng tin ca newRow thm. y c thay i settings ca Table, mc nh th ct FirstName khng c Null, mnh y sa li pht cho php null lun, v thay i dng u tin ct City. Sau thm dng mi vo DataSet. Chc khng c g ni nhiu v ci ny nh. Thay i d liu trong Data Source Quay v Adapter, update thng tin th ta dng cc thuc tnh : UpdateCommand, InsertCommand, DeleteCommand, cn SelectCommand th khng phi v n cung cp SqlCommand thc thi v chng nh hng g n x hi c s d liu . Thuc tnh UpdateCommand Nh tn gi ni ln y l thc hin Statement thay i d liu trong database hay l cu lnh UPDATE.SET V d thc hin Update : Visual C# Code: La chn code | n/Hin code da.UpdateCommand = new SqlCommand(UPDATE employees SET city = + dt.Rows[0][city] + WHERE employeeid = + dt.Rows[0] [employeeid] + , conn); // Thay i d liu ca bng employee ln database source da.Update(ds, employees); Di y t lm v d minh ha s dng lun, t s xi tham s trong lnh truyn vo SQL cho thc dng hehe Visual C# Code: La chn code | n/Hin code using System; using System.Data; using System.Data.SqlClient; namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string qry = @"SELECT * FROM employees WHERE country = 'UK' "; string upd = @"UPDATE employees SET city = @city WHERE }

employeeid = @employeeid "; // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(qry, conn); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "employees"); // Ly thng tin Table vo DataTable DataTable dt = ds.Tables["employees"]; // Sa dng u tin dt.Rows[0]["city"] = "Seoul"; // In ra mn hnh xem s thay i trong DataSet foreach (DataRow row in dt.Rows) { Console.WriteLine("{0} {1} {2}", row["firstname"].ToString().PadLeft(14), row["lastname"].ToString().PadRight(15), row["city"]); } // Tin hnh update vo database Source // to command trc SqlCommand cmd = new SqlCommand(upd, conn); // X l cc Parameter trong command cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city"); SqlParameter param = cmd.Parameters.Add("@employeeid", SqlDbType.Int, 4, "employeeid"); param.SourceVersion = DataRowVersion.Original; // UPDATE da.UpdateCommand = cmd; da.Update(ds, "employees"); } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } }

} bit code trn ra kt qu th no th, m SQL Server Management Studio 2005

Express ra ri run query sau :


Code:

use Northwind SELECT firstname,lastname,city FROM employees WHERE country = 'UK' Bn s thu c cc value cn thit. Sau run code trn, ri run li query SQL trn, s thy dng trn cng city s b thay i thnh Seoul. __________________ [Android-Newbie] - Tutorials / Guide / Learning / Training Android for beginners -> Click to visit me at : http://xjaphx.wordpress.com/ (o) Feel free to learn, feel free to ask w/ free support (o)
c chnh sa ln cui bi Xcross87 : 03-08-2007 lc 10:57 AM.

#2 03-08-2007, 10:47 AM Ngy gia nhp: 09 2006 Ni : /usr/share/.hack@ Bi vit: 1,483

Xcross87
Thnh vin nhit tnh

Thuc tnh InsertCommand V d th Insert thm mt dng heng Visual C# Code: using System; using System.Data; using System.Data.SqlClient; La chn code | n/Hin code

namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string qry = @"SELECT * FROM employees WHERE country = 'UK' "; string ins = @"INSERT INTO employees (firstname, lastname, titleofcourtesy, city, country) VALUES (@firstname, @lastname, @titleofcourtesy, @city, @country) "; // To connection SqlConnection conn = new SqlConnection(connString); try {

// To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(qry, conn); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "employees"); // Ly thng tin Table vo DataTable DataTable dt = ds.Tables["employees"]; // To thm row mi DataRow newRow = dt.NewRow(); newRow["firstname"] = "Pete"; newRow["lastname"] = "Houston"; newRow["titleofcourtesy"] = "Sir"; newRow["city"] = "Seoul"; newRow["country"] = "South Korea"; dt.Rows.Add(newRow); // Hin th thng tin cc rows trong DataSet foreach (DataRow row in dt.Rows) { Console.WriteLine("{0} {1} {2}", row["firstname"].ToString().PadRight(15), row["lastname"].ToString().PadLeft(15), row["city"]); } // Lm vic vi Insert SqlCommand cmd = new SqlCommand(ins, conn); cmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10, "firstname"); cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 20, "lastname"); cmd.Parameters.Add("@titleofcourtesy", SqlDbType.NVarChar, 25, "titleofcourtesy"); cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city"); cmd.Parameters.Add("@country", SqlDbType.NVarChar, 15, "country"); // Tin hnh insert vo database Source da.InsertCommand = cmd; da.Update(ds, "employees"); } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); }

} }

Rt n gin nn mnh khng gii thch g y Thuc tnh DeleteCommand Ci ny cc bn th nghim t vit code thc hnh nh. Gii thiu v SqlCommandBuilder Nhn li cc code trn update d liu ln DataSource cng nhn qu di v hi b NN khi vit code. Mt nht l khon debug, qu rc ri v phc tp. V vy m thng cu SqlCommandBuilder trong h ra i phc v vic to cc statement INSERT, UPDATE, DELETE mt cch t ng. Thm ch l sau khi thay i thng tin trn data source th bn phi gi method RefreshSchema ca commandbuilder cp nht thng tin ca metadata tng ng. Lm v d thm mt dng vo database dng SqlCommandBuilder nha Visual C# Code: La chn code | n/Hin code using System; using System.Data; using System.Data.SqlClient; namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True; Database = Northwind"; // To SQL query string qry = @"SELECT * FROM employees WHERE country = 'UK' "; // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(qry, conn); // To commandbuider SqlCommandBuilder cb = new SqlCommandBuilder(da); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "employees"); // Ly thng tin Table vo DataTable DataTable dt = ds.Tables["employees"]; // To thm row mi DataRow newRow = dt.NewRow();

newRow["firstname"] = "Pete"; newRow["lastname"] = "Houston"; newRow["titleofcourtesy"] = "Sir"; newRow["city"] = "Seoul"; newRow["country"] = "South Korea"; dt.Rows.Add(newRow); // Hin th thng tin cc rows trong DataSet foreach (DataRow row in dt.Rows) { Console.WriteLine("{0} {1} {2}", row["firstname"].ToString().PadRight(15), row["lastname"].ToString().PadLeft(15), row["city"]); } da.Update(ds, "employees"); } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } }

} Thy hay khng? Dng SqlCommandBuilder th b i c bao nhiu on cn thit. So snh vi bi InsertCommand trn chc l ngn hn c m c code d hiu hn. DataSet v XML Bn mun extract d liu trong DataSet ra mt file nh dng XML ? Liu c cn i hi kin thc XML lm vic ?...heheh . Khng cn bit v XML vn extract c Mt v d vit lu d liu trong DataSet di dng XML. Visual C# Code: La chn code | n/Hin code using System; using System.Data; using System.Data.SqlClient; namespace MSSQL_Server { class Database { static void Main(string[] args) { // To connection strin string connString = @"Server = .\SQLEXPRESS; Integrated Security = True;

Database = Northwind"; // To SQL query string qry = @"SELECT firstname,lastname, city FROM employees WHERE country = 'UK' "; // To connection SqlConnection conn = new SqlConnection(connString); try { // To Adapter SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(qry, conn); // To commandbuider SqlCommandBuilder cb = new SqlCommandBuilder(da); // To v lp y DataSet DataSet ds = new DataSet(); da.Fill(ds, "employees"); // Extract ra file di dng XML ds.WriteXml(@"P:\database.xml"); } catch (Exception e) { // Bt li Console.WriteLine(e.Message); } finally { // ng kt ni conn.Close(); } } }

} Sau check file database.xml nh t trn trong code kim tra ^_^. Bn s thy th <NewDataSet> chnh l name ca DataSet. Bn c th ty thay i DataSetName Thm mt ch na : bn c th dng DataTable ly thng tin trong bng t DataAdapter thng qua method Fill da.Fill(dt); Trong ADO.NET c mt thnh phn rt c bit c tn l Typed DataSet. Mnh s ni v ci ny sau. Bi vit c l qu di nn kt thc y.

Th 2

Sng 6h TV

Ti 11h30 N

Th 3

Sng 6h NP

Ti 11h30 TV

Th 4

Sng 6h N

Ti 11h30 NP

Th 5

Sng 6h TV

Ti 11h30 N

Th 6

Sng 6h NP

Ti 11h30 N

Th 7

Sng 6h TV

Ti 11h30 N

Ch nht

Sng 6h TV

Ti 11h30 NP

nh gi KQ Sn ch g a Ti nh gi KQ Sn C g Ti nh gi KQ Sn C g Ti nh gi KQ Sn g Ti nh gi KQ Sn g Ti nh gi KQ Sn g Ti nh gi KQ Sn g Ti

Tun 1 : 5/3/12

You might also like