Ti System.Data.SqlClient namespace vo project B khi to: SqlConnection() 1: SqlConnection() 2: SqlConnection(string connectionString) Khi to mt i tng mi SqlConnection bng pht biu sau: SqlConnection mySqlConnection = new SqlConnection(); mySqlConnection.ConnectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; server ch nh tn my tnh c trinh SqlServer ang chy. database ch nh tn c s d liu uid tn ti khan pwd m n nhp ch : ch thit lp connectionString khi i tng kt ni ca bn ng KT NI TRC TIP: string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; SqlConnection mySqlConnection = new SqlConnection(connectionString);
KT NI N GIN:
SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
Listing 7.1: MYSQLCONNECTION.CS /* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server database */
using System; using System.Data; using System.Data.SqlClient;
class MySqlConnection { public static void Main() { // formulate a string containing the details of the // database connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";
// create a SqlConnection object to connect to the // database, passing the connection string to the constructor SqlConnection mySqlConnection = new SqlConnection(connectionString);
// open the database connection using the // Open() method of the SqlConnection object mySqlConnection.Open();
// close the database connection using the Close() method // of the SqlConnection object mySqlConnection.Close(); } } The output from this program is as follows: mySqlConnection.ConnectionString = server=localhost;database=Northwind;uid=sa; mySqlConnection.ConnectionTimeout = 15 mySqlConnection.Database = Northwind mySqlConnection.DataSource = localhost mySqlConnection.PacketSize = 8192 mySqlConnection.ServerVersion = 08.00.0194 mySqlConnection.State = Open mySqlConnection.WorkstationId = JMPRICE-DT1
B NHM NHNG KT NI(CONNECTION POOLING)
S m v ng kt ni tiu ph nhiu thi gian . do d ADO .NET t ng lu gi nhng kt ni trong Mt b cha , n cung cp mt s ci tin ln v thc thi kt ni . bn khng cn ch i mt kt ni Trng n c s d liu trong khi mt kt ni c hiu lc. Khi bn ng mt kt ni , n cha thc s ng , kt ni ca bn c nh du l cha dng n v c d tr trong mt b cha, sn sng s dng tr li Sau nu bn cung cp chi tit kt ni tng t trong connection string ( database name, uid, password) th kt ni d tr trong pool s c khi phc v bn tip tc s dng n truy cp d liu
Khi s dng i tong Sqlconnection bn c th bn c th ch nh s lng kt ni ln nht cho php trong pool bng cch ch nh Max pool size (mc nh l 100) v Min pool Size .
SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5");
using System; using System.Data; using System.Data.SqlClient;
class ConnectionPooling { public static void Main() { // create a SqlConnection object to connect to the database, // setting max pool size to 10 and min pool size to 5 SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5");
// open the SqlConnection object 10 times for (int count = 1; count <= 10; count++) { Console.WriteLine("count = "+ count);
// create a DateTime object and set it to the // current date and time DateTime start = DateTime.Now;
// open the database connection using the // Open() method of the SqlConnection object mySqlConnection.Open();
// subtract the current date and time from the start, // storing the difference in a TimeSpan TimeSpan timeTaken = DateTime.Now - start;
// display the number of milliseconds taken to open // the connection Console.WriteLine("Milliseconds = "+ timeTaken.Milliseconds);
// display the connection state Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);
// close the database connection using the Close() method // of the SqlConnection object mySqlConnection.Close(); } } } The output from this program is as follows: count = 1 Milliseconds = 101 mySqlConnection.State = Open count = 2 Milliseconds = 0 mySqlConnection.State = Open count = 3 Milliseconds = 0 mySqlConnection.State = Open count = 4 Milliseconds = 0 mySqlConnection.State = Open count = 5 Milliseconds = 0 mySqlConnection.State = Open count = 6 Milliseconds = 0 mySqlConnection.State = Open count = 7 Milliseconds = 0 mySqlConnection.State = Open count = 8 Milliseconds = 0 mySqlConnection.State = Open count = 9 Milliseconds = 0 mySqlConnection.State = Open count = 10 Milliseconds = 0 mySqlConnection.State = Open
TRUY XUT TRANG THAI CA I TNG KT NI:
Bn s dng thuc tnh state ca kt ni lt thng tin v trng thi hin ti ca kt ni n c s d liu, thuc tnh state tr v mt hng t bng lit k connectionstate. Table 7.4: ConnectionState CONSTANTS TN HNG M T Broken Hng kt ni. iu ny sy ra sau khi bn m i tng kt ni. bn c th ng kt ni v m li Closed Kt ni ng. Connecting Kt ni ang thit lp s truy cp n c s d liu. Executing Kt ni ang thc thi mt lnh (command). Fetching Kt ni ang nhn thng tin t c s d liu. Open Kt ni ang m.
Th d sau y s dng thuc tnh state kim tra trang thi kt ni c phi ang ng khng trc khi m kt ni
if (mySqlConnection.State == ConnectionState.Closed) { mySqlConnection.Open(); }
S DNG CC BIN C CA I TNG KT NI:
Nhng lp kt ni c hai bin c hu ch: StateChange v InfoMessage.
BIN C StateChange:
Bin c StateChange pht ra khi trng thi cua kt ni thay i, bn c th s dng bin c ny theo di trng thi ca i tng kt ni.
Phng thc nm gi mt bin c c bit nh mt b s l s kin (event handler ). Bn gi phng thc ny khi mt s kin c trng c tung ra. Tt c cc phng thc s l bin c u phi tr v mt gi tr void v nhn hai tham s. tham s th nht l mt i tng ( ca lp System.Object), v n i din cho i tng pht ra bin c.
Ch : lp System.Oject l lp c s ca tt c cc lp. ni cch khc , tt c cc lp u bt ngun t lp System.Object.
Tham s Second l mt i tng ca lp bt ngun t lp System.EventArgs . lp System.EventArgs l lp c s nm gi d liu v bin c v m t nhng chi tit v bin c. trong trng hp ca bin c StateChange , i tng Second ny l thuc v lp StateChangeEventArgs
Th d di y nh ngha mt phng thc tn StateChangeHandler s l bin c StateChange . ch rng tham s Second cho phng thc ny l i tng StateChangeEventArgs. Bn ly thng tin trng thi nguyn thy ca kt ni s dng thuc tnh OriginalStatae ca i tng ny, v thng tin trng thi hin ti s dng thuc tnh CurrentState.
public static void StateChangeHandler(object mySender, StateChangeEventArgs myEvent) { Console.WriteLine("mySqlConnection State has changed from "+ myEvent.OriginalState + "to "+ myEvent.CurrentState ); theo di mt bin c, bn phi ng k phng thc s l bin c (event handler method) Vi bin c . th d: pht biu di y ng k phng thc s l bin c _ StateChangeHandler() vi bin c StateChange ca i tng mySqlConnection
NG K MT PHNG THC S L BIN C:
mySqlConnection.StateChange += new StateChangeEventHandler(StateChangeHandler); bt c khi no bin c StateChange pht khi , th phng thc StateChangeHandler() s c gi, , th phng thc StateChangeHandler() s c gi, n hin th trng thi hin ti ca i tng mySqlConnection
/* StateChange.cs illustrates how to use the StateChange event */
using System; using System.Data; using System.Data.SqlClient;
class StateChange { // define the StateChangeHandler() method to handle the // StateChange event public static void StateChangeHandler( object mySender, StateChangeEventArgs myEvent) { Console.WriteLine("mySqlConnection State has changed from "+ myEvent.OriginalState + "to "+ myEvent.CurrentState); }
public static void Main() { // create a SqlConnection object SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
// monitor the StateChange event using the StateChangeHandler() method mySqlConnection.StateChange += new StateChangeEventHandler(StateChangeHandler);
// open mySqlConnection, causing the State to change from Closed // to Open Console.WriteLine("Calling mySqlConnection.Open()"); mySqlConnection.Open();
// close mySqlConnection, causing the State to change from Open // to Closed Console.WriteLine("Calling mySqlConnection.Close()"); mySqlConnection.Close(); } }
The output from this program is as follows: Calling mySqlConnection.Open() mySqlConnection State has changed from Closed to Open Calling mySqlConnection.Close() mySqlConnection State has changed from Open to Closed
BIN C InforMessage :
Bin c InfoMessage khi pht khi c s d liu tr v mt thng tin cnh bo to ra t c s d liu. Bn s dng bin c InfoMessage theo di nhng thng bo ny. c c nhng thng bo ny , bn c ni dung ca tp hp li (Errors collection) t i tng SqlInfoMessageEventArgs.
Bn c th cung cp thng tin v thng bo li nh s dng SQL Server PRINT hoc nhng pht biu RAISEERROR, c m t trong chng 4, gii thiu v lp trnh Transact-SQL.
Phng thc InfoMessageHandler() di y c s dng s l bin c InfoMessage . ch rng s s dng tp hp ERRORS (Errors collection) hin th thng bo.
public static void InfoMessageHandler(object mySender, SqlInfoMessageEventArgs myEvent) { Console.WriteLine("The following message was produced:\n" +myEvent.Errors[0]); }
Ch thch : nu bn ang s dng nhng b cung cp qun l OLE DB, bn thay th SqlInfoMessageEventArgs vi OleDbInfoMessageEventArgs.nu bn ang s dng b cung cp qun l ODBC , bn thay th SqlInfoMessageEventArgs vi OdbcInfoMessageEventArgs..
Listing 7.4: INFOMESSAGE.CS
/* InfoMessage.cs minh ha s dng bin c InfoMessage nh th no */
using System; using System.Data; using System.Data.SqlClient; class InfoMessage { // nh ngha phng thc InfoMessageHandler() s l s c // InfoMessage event public static void InfoMessageHandler( object mySender, SqlInfoMessageEventArgs myEvent) { Console.WriteLine("The following message was produced:\n" + myEvent.Errors[0]); }
public static void Main() { // create a SqlConnection object SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
// monitor the InfoMessage event using the InfoMessageHandler() method mySqlConnection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
// open mySqlConnection mySqlConnection.Open();
// create a SqlCommand object SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// run a PRINT statement mySqlCommand.CommandText = "PRINT 'This is the message from the PRINT statement'"; mySqlCommand.ExecuteNonQuery();
// run a RAISERROR statement mySqlCommand.CommandText = "RAISERROR('This is the message from the RAISERROR statement', 10, 1)"; mySqlCommand.ExecuteNonQuery();
// close mySqlConnection mySqlConnection.Close(); } }
The output from this program is as follows: The following message was produced: System.Data.SqlClient.SqlError: This is the message from the PRINT statement The following message was produced: System.Data.SqlClient.SqlError: This is the message from the RAISERROR statement
TO MT I TNG KT NI S DNG VISUAL STUDIO .NET
to mt i tng kt ni s dng Visual Studio .NET, bn ko mt i tng SqlConnection T tab data trong toolbox n form ca bn . bn s gi li mt i tng kt ni (SqlConnection) Cho php bn kt ni vi c s d liu SQL Server. Bn cng c th lm tng t vi i tng OleDbConnection kt ni vi c s d liu OLE DB.
Hnh 7.1 : to mt i tng SqlConnection vi Visual Studio .NET
Mt khi bn to mt i tng SqlConnection, i tng ny s xut hin trn khay di form. Khay ny c s dng cha nhng thnh phn khng hin th nh i tng SqlConnection. Nhng i tng khc hin th trn khay l i tng SqlCommand. Nhng i tng ny c xem Khng hin th v chng khng c nhn thy khi bn khi chy form. ng nhin bn vn c th lm vic vi chng mt cch trc quan khi thit k form.
Bn phi ca form, bn ch n ca s thuc tnh, ni m bn s dng thit t nhng thuc tnh Cho i tng SqlConnection. thit t thuc tnh ConnectionString_ m t chi tit v c s d liu kt ni , bn c th g trc tip chui kt ni vo hoc click vo danh sch s xung v thit t ConnectionString mt cch trc quan. lm iu ny, bn chn New Connection trong damh sch S xung, s hin th hp thai Data Link Properties. Hp thai ny cha bn Tab, Tab Provider cho php bn chn la kiu ca b cung cp m bn mun kt ni, nh hnh 7.2
Hnh 7.2: chn la b cung cp d liu Click nt Next chuyn n Tab Connection ( bn cng c th nhn Tab Connection cch trc tip) Ni bn nhp chi tit v kt ni n c s d liu ca bn. nh hnh 7.3 di y
Hnh 7.3: nhp nhng chi tit v kt ni
Cnh bo: v nhng l do an tan, khng ch hp check Allow Saving Password. Nu bn thc hin iu ny Password ca bn s c lu trong code, v ngi no 1o c th c dc Password ca bn trong code. Sau khi bn nhp chi tit v kt ni ca bn, bn c th click nt Test Connection bo m nhng chi tit l chnh sc . click OK lu thit lp Trn my tnh ca ti, thuc tnh ConnectionString ca i tng kt ni n c s d liu SQL Server Northwind c thit lp nh sau:
data source=localhost;initial catalog=Northwind;persist security info=False; user id=sa;pwd=sa;workstation id=JMPRICE-DT1;packet size=4096
bn c th thm code cho mt bin c trong VS .NET. th d, bn mun thm code cho min c State- change ca i tng CqlConnection1 c to. lm iu ny, trc tin chn SqlConnection1 trn khay, ri click vo nt Events (biu tng tia st) bn trn ca s properties, mt danh sch cc bin c ca i tng SqlConnection1 s c hin th trong ca s properties. Double click vo tn ca bin c m bn mun vit m code. VS >NET s hin th khung code v to Mt khung sn ca phng thc event handler cho bn, nh trnh by trong hnh 7.7 di y. V tr con nhy s l ni bn nhp code.
private void sqlConnection1_StateChange( object sender, System.Data.StateChangeEventArgs e) { // an code bn nhp di y Console.WriteLine("State has changed from "+ e.OriginalState + "to "+e.CurrentState );
Sau khi bn bn to i tng SqlConnection bn c th lm vic vi cc i tng ADO >NET khc nh i tng SqlCommand v.v bn s hc cch th hin iu ny vi VS .NET trong chng 8.
CHNG 8: THC THI CC LNH C S D LIU: EXECUTING DATABASE COMMANDS
Nhng lnh v c s d liu c th thi bi i tng Command, v l b phn ca b cung cp c qun l. C ba lp Command : SqlCommand, OleDbCommand, v OdbcCommand. Bn s dng i tng command thc thi mt pht biu SQL Select, Insert, Update, hoc Delete. Bn cng c th s dng i tng Command gi mt Stored procedure ( phng thc c thit lp sn bi ngn ng SQL server c d tr trong c s d liu) , hoc truy xut nhng hng v ct trong mt bng ch nh; i tng Command truyn thng vi c s d liu nh s dng i tng Connection
LP SQLCOMMAND: Bn s dng mt i tng ca lp SqlCommand th thi mt lnh tren mt c s d liu SQL Server, mt i tng ca lp OleDbCommand th thi mt lnh trn bt c c s d liu no h tr OLE DB, nh Oracle hoc Access, v mt i tng ca lp OdbcCommand thc thi mt lnh trn c s d liu no htr ODBC.bng di y trinh by mt vi thuc tnh v phng thc ca SqlCommand.
Table 8.1: SqlCommand PROPERTIES THUC TNH KIU M T CommandText string Ly hoc thit t pht biu SQL, gi stored procedure , hoc bng truy xut d liu CommandTimeout int Ly hoc thit t s giy ch i trc khi kt thc mt c gng thc thi lnh (command). Thi gian mc nh l 30 giy. CommandType CommandType Ly hoc thit t mt gi tr cho bit thuc tnh CommandText c th hin nh th no. Nhng gi tr hp l l : CommandType.Text, CommandType .StoredProcedure, v CommandType .TableDirect. Text cho bit command l mt pht biu SQL. StoredProcedure cho bit command l mt lnh gi stored procedure . TableDirect cho bit tn ca mt bng, m t tt c cc hng v ct c truy xut. mc nh l Text. Connection string Tr v tn ca mt kt ni c s d liu. DesignTimeVisible bool Ly hoc thit t mt gi tr Boolean cho bit mt i tng Command c c hin th trong mt Conntrol ca b thit k windows form. Gi tr mc nh l false. Parameters SqlParameterCollection Tr v nhng tham s( parameters) (nu c) cung cp cho Command . khi s dng mt kt ni (SqlConnection) nhng tham s ny c lu tr trong mt i tng SqlParameterCollection Transaction SqlTransaction Ly hoc thit t giao dch d liu cho Command (database transaction UpdatedRowSource UpdateRowSource Ly hoc thit t nhng kt qu ca thc thi Command c ng dng nh th no n mt i tng DataRow khi mt phng thc Update() ca i tng DataAdapter c gi. PHNG THC GI TR TR V M T Cancel() void Hy b thc thi ca lnh (command). CreateParameter() SqlParameter To mt tham s mi cho command. ExecuteNonQuery() int S dng th thi nhng pht biu SQL khng tr v mt tp gi tr. Nhng pht biu ny bao gm INSERT, UPDATE, v DELETE, nhng pht biu thuc ngn ng nh ngha d liu, hoc nhng lnh gi Strored Procedure Khng tr v mt tp d liu. N tr v mt gi tr kiu Int l s hng ca c s d liu b nh hng bi thc thi Command, nu c. ExecuteReader() SqlDataReader c s dng thc thi nhng pht biu SQL SELECT, nhng lnh bng trc tip (TableDirect commands) Hoc Stored Procedure tr v mt tp gi tr trong i tng DataReader. ExecuteScalar() object c s dng thc thi nhng pht biu SQL SELECT tr v mt gi tr n (nhng gi tr khc b b qua). Kt qu tr v ca Command l mt i tng. ExecuteXmlReader() XmlReader c s dng thc thi nhng pht biu SQL SELECT tr v c s d liu XML. Tr v tp kt qu trong mt i tng XmlReader. Ch ng dng cho lp SqlCommand. Prepare() void To mt bn dch d phng ca command,i khi , nhng kt qu nhanh hn trong s thc thi command. PHNG THC GI TR TR V M T ResetCommandTimeout() void Thit lp li thuc tnh CommandTimeout v gi tr mc nh. Ch thch Mc d lp SqlCommand c dnh ring cho SQLServer, rt nhiu thuc tnh v phng thc tong lp ny cng tng t nh cc thuc tnh v phng thc trong nhng lp OleDbCommand v OdbcCommand. K xo Bn thc s s lm tt hn khi t b T-SQL EXECUTE Command v s dng CommandType.StoredProcedure thc thi mt stored procedure. Bi v bn c th c c nhng gi tr c tr v t mt Stored Procedure thng qua pht biu RETURN, ci m bn c th thc hin khi thit nh CommandType l Stored Procedure.
TO MT I TNG SQLCOMMAND:
c hai cch to mt i tng SqlCommand: s dng mt trong trong s nhng b khi to SqlCommand. gi phng thc CreateCommand() ca mt i tng SqlConnection. CH : bn c th s d dng nhng cch tng t nh trnh by di y to i tng OleDbCommand hoc OdbcCommand.
CommandText : cha pht biu SQL ca bn, lnh gi stored procedure, hoc bng truy xut d liu. mySqlConnection: l i tng SqlConnection. mySqlTransaction: l i tng SqlTransaction ca bn.
Trc khi bn s dng mt i tng SqlCommand u tin bn cn c mt i tngSqlConnection, giao tip vi mt c s d liu SQL Server:
Tip theo bn c th to mt i tng SqlCommand mi s dng pht biu sau:
SqlCommand mySqlCommand = new SqlCommand();
Sau thit t thuc tnh Connection ca mySqlCommand l mySqlConnection:
mySqlCommand.Connection = mySqlConnection;
v i tng mySqlCommand s s dng ngay i tng mySqlConnection giao tip vi c s d liu. by gi, thuc tnh CommandType ca i tng Connection s quyt nh kiu ca Command c th thi. Bn c th s dng bt c gi tr no trong kiu lit k System.Data.CommandType ch nh thuc tnh CommandType. Table 8.3: CommandType ENUMERATION VALUES GI TR M T Text Cho bit command l mt pht biu SQL. Text l gi tr mc nh. StoredProcedure Cho bit Command l mt lnh gi stored procedure. TableDirect Cho bit tn ca mt bng, m tt c nhng hng v ct s c truy xut. ch thch: nhng i tng SqlCommand khng h tr TableDirect. Bn phi s dng mt i tng ca mt trong nhng lp Command khc thay th.
Bn s tm hiu cch s dng ba kiu Command ny trong chng ny. By gi ti s t trong tm vo kiu Text Command, l mt pht biu SQL. Bn c th thit t Command c th thi s dng thuc tnh CommandText ca i tng Command ca bn. th d sau y thit t thuc tnh CommandText ca mySqlCommand vi mt pht biu SELECT .. mySqlCommand.CommandText = SELECT TOP 10 CustomerID, CompanyName, ContactName, Adrress + FROM Customers + ORDER BY CustomerID;
Bn cng c th t i tng Command v Connection vo b khi to trong cng mt bc vi vic to mt Command. Th d:
SqlCommand mySqlCommand = new SqlCommand( SELECT TOP 5 CustomerID, CompanyName, ContactName, Address + FROM Customers , mySqlConnextion);
trong phn k tip , bn s hc cch to mt i tng SqlCommand s dng phng thc CreatCommand() ca mt i tng SqlConnection.
KHI TO MT I TNG SqlCommand S DNG PHNG THC CreatCommand().
Ngai cch khi to mt i tng SqlCommand s dng nhng b khi to, bn c th s dng phng thc CreatCommand ca i tng SqlConnection. Phng thc ny tr v mt i tng SqlCommand mi. th d:
i tng mySqlCommand s s dng mySqlConnection tng tc vi c s d liu.
THC THI NHNG PHT BIU SELECT V NHNG LNH TABLEDIRECT:
Mt TableDirect Command thc ra l mt pht biu SELECT, n tr v tt c nhng hng v ct ca mt bng ch nh. Mt i tng Comand c ba phng thc bn c th s dng thc thi mt pht biu SELECT hoc mt TableDirect Command.
Table 8.4: NHNG PHNG THC TRUY XUT THNG TIN T CS D LIU PHNG THC KIU TR V M T ExecuteReader() SqlDataReader c dng thc thi mt pht biu SQL SELECT, TableDirect Commands hoc cc lnh gi stored procedure ,n tr v mt tp hp Table 8.4: NHNG PHNG THC TRUY XUT THNG TIN T CS D LIU PHNG THC KIU TR V M T kt qutrong mt i tng DataReader. ExecuteScalar() object c dng thc thi nhng pht biu SQL SELECT v tr v mt gi tr n (b qua nhng gi tr khc). Gi tr n c tr v nh mt i tng. ExecuteXmlReader() XmlReader c dng thc thi nhng pht biu SQL SELECT v tr v mt XML data. Tp hp kt qu tr v trong mt i tng XmlReader . ch ng dng cho lp SqlCommand.
THC THI PHT BIU SELECT S DNG S DNG PHNG THC ExecuteReader():
Hy xem mt th d : thc thi mt pht biu SELECT s dng phng thc ExecuteReader(). Phng thc ny tr v nt tp hp kt qu trong mt i tng DataReader, m bn c th dng n c nhng hng c tr v t c s d kiu. th d , code sau y khi to nhng i tng cn thit v thc thi mt pht biu SELECT truy xut 05 dng u tin t bng Customers:
K xo: bn ch rng ti khng gi phng thc Open() ca i tng SqlConnection cho n khi ngay trc s gi phng thc ExecuteReader() ca i tng SqlCommand. y l s nh trc. Bng cch m kt ni vo thi im rt cui cng, bn gim thiu chi ph thi gian kt ni vi c s d liu v do gn gi nhng ti nguyn c s d liu.
Tp kt qu c tr v bi mySqlCommand c lu tr trong mySqlDataReader. V ri bn s c nhng hng t mySqlDataReader s dng phng thc Read(). Phng thc ny tr v mt gi tr Boolean, true nu Nh c mt hng khc c, ngc li s tr v gi tr false. Bn c th c mt gi tr ring r ca mt ct trong mt hng t mySqlDataReader bng cch thng qua ch nh tn ca ct trong cp du ngoc vung. Th d, c ct CustomerID, bn dng mySqlDataReader[CustomerID].
Ch : bn cng c th ch nh ct m bn mun c bng cch t mt gi tr s (ch s ct trong tp hp) trong cp du ngoc vung. Th d, mySqlDataReader[0] cng tr v gi tr ca ct CustomerID. 0 tng ng vi ct u tin trong bng, nh trong th d ny l ct CustomerID.
Bn cng c th s dng phng thc Read() trong mt pht biu while loop c tun t mi lt mt hng, Nh trnh by trong v d di y:
DI Y L MT CHNG TRNH Y V S DNG I TNG SQLDATAREADER:
/* ExecuteSelect.cs illustrates how to execute a SELECT statement using a SqlCommand object */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteSelect { public static void Main() { // create a SqlConnection object to connect to the database SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// create a SqlCommand object SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to // the SELECT statement mySqlCommand.CommandText = "SELECT TOP 5 CustomerID, CompanyName, ContactName, Address " + "FROM Customers " + "ORDER BY CustomerID";
// open the database connection using the // Open() method of the SqlConnection object mySqlConnection.Open();
// create a SqlDataReader object and call the ExecuteReader() // method of the SqlCommand object to run the SQL SELECT statement SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
// read the rows from the SqlDataReader object using // the Read() method while (mySqlDataReader.Read()) { Console.WriteLine("mySqlDataReader[\" CustomerID\"] = " + mySqlDataReader["CustomerID"]); Console.WriteLine("mySqlDataReader[\" CompanyName\"] = " + mySqlDataReader["CompanyName"]); Console.WriteLine("mySqlDataReader[\" ContactName\"] = " + mySqlDataReader["ContactName"]); Console.WriteLine("mySqlDataReader[\" Address\"] = " + mySqlDataReader["Address"]); }
// close the SqlDataReader object using the Close() method mySqlDataReader.Close();
// close the SqlConnection object using the Close() method mySqlConnection.Close(); }
The output from this program is as follows: mySqlDataReader["CustomerID"] = ALFKI mySqlDataReader["CompanyName"] = Alfreds Futterkiste mySqlDataReader["ContactName"] = Maria Anders mySqlDataReader["Address"] = Obere Str. 57 mySqlDataReader["CustomerID"] = ANATR mySqlDataReader["CompanyName"] = Ana Trujillo3 Emparedados y helados mySqlDataReader["ContactName"] = Ana Trujillo mySqlDataReader["Address"] = Avda. de la Constitucin 2222 mySqlDataReader["CustomerID"] = ANTON mySqlDataReader["CompanyName"] = Antonio Moreno Taquera mySqlDataReader["ContactName"] = Antonio Moreno mySqlDataReader["Address"] = Mataderos 2312 mySqlDataReader["CustomerID"] = AROUT mySqlDataReader["CompanyName"] = Around the Horn mySqlDataReader["ContactName"] = Thomas Hardy mySqlDataReader["Address"] = 120 Hanover Sq. mySqlDataReader["CustomerID"] = BERGS mySqlDataReader["CompanyName"] = Berglunds snabbkp mySqlDataReader["ContactName"] = Christina Berglund mySqlDataReader["Address"] = Berguvsvgen 8
KIM SAT HNH VI CA LNH(COMMAND) S DNG S DNG PHNG THC ExecutReader()
Phng thc ExecuteReader() chp nhn mt tham s ty chn dng iu khin hnh vi ca Command. Nhng gi tr ca tham s ny n t lp lit k System.Data.CommandBehavior, nhng gi tr ny c trnh by trong bng 8.5 di y.
Gi tr Mt CloseConnection Ch nh rng khi i tng SqlDataReader c ng ,i tng SqlConnection cng ng theo. Default Ch nh rng i tng Command c th tr v nhiu tp hp kt qu. KeyInfo Ch nh i tng Command ch tr v thng tin v nhng ct khachnh trong tp hp kt qu SchemaOnly Ch nh i tng Command ch tr v thng tin lin quan n cc ct. SequentialAccess Cho php mt i tng DataReader c nhng hng c nhng ct cha ng nhng gi tr nh phn ln. S truy cp tun t to cho DataReader c d liu nh mt lung. v bn s dng phng thc GetBytes() hay GetChars() ca i tng DataReader c lung ny. Ch : bn s hc chi tit v i tng DataReader trong chng ti. Gi tr Mt SingleResult Ch nh i tng Command tr v mt tp kt qu n. SingleRow Ch ng i tng Command tr v mt mt hng n.
S DNG THUC TNH HNH VI CA COMMAND: SingleRow
Bn s dng hnh vi lnh : SingleRow ch nh i tng Command tr v mt hng n. Th d, cho l bn c mt i tng Command tn mySqlCommand vi thuc tnh CommandText c gn nh sau:
Mc d pht biu SELECT trc ch nh tt c nhng hng u s c truy xut t bng nhng sn phm,
Di y l minh ha hiu qu ca vic s dng CommandBehavior. SingleRow. /* SingleRowCommandBehavior.cs illustrates how to control the command behavior to return a single row */ using System; using System.Data; using System.Data.SqlClient;
class SingleRowCommandBehavior { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// pass the CommandBehavior.SingleRow value to the // ExecuteReader() method, indicating that the Command object // only returns a single row SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.SingleRow);
The output from this program is as follows: mySqlDataReader["ProductID"] = 1 mySqlDataReader["ProductName"] = Chai mySqlDataReader["QuantityPerUnit"] = 10 boxes x 20 bags mySqlDataReader["UnitPrice"] = 18
S DNG THUC TNH HNH VI CA COMMAND: SchemaOnly
Bn s dng hnh vi Command: SchemaOnly ch nh i tng Command ch tr v thng tin ca nhng ct c truy xut bi mt pht biu SELECT, hay tt c nhng ct nu bn s dng mt Command TableDirect.
Th d: cho l bn c mt i tng Command tn mySqlCommand vi thuc tnh CommandText c gn nh di y:
trong th d ny, t nhng ct ProductID, ProductName, v UnitPrice ca bng Products c s dng trong pht biu SELECT trc , thng tin v nhng ct c truy xut thay v nhng gi tr ct.
bn cng c c thng tin v nhng ct s dng phng thc GetSchemaTable() ca i tng SqlDataReader. Phng thc GetSchemaTable() tr li mt i tng DataTable vi nhng ct cha nhng chi tit ca nhng ct c s d liu c truy xut:
ch m ny c hai vng lp lng nhau. Vng lp pha ngoi lp li qua nhng i tng DataRow trong myDataTable, v vng lp bn trong lp li qua nhng i tng DataColumn trong DataRow hin thi. ng lo lng qu nhiu v nhng chi tit v vic truy nhp mt DataTable . bn s hc chi tit ny trong chng 10 ,s dng i tng Dataset lu tr d liu.
Pht biu if trong vng lp Foreach (vng lp trong) cn mt cht gii thch. iu m Ti ang lm l kho st myDataColumn xem n cha ProviderType hay khng. ProviderType cha mt gi tr s ch nh kiu SQL Sever ca ct d liu. ti buc s ny vo System.Data.SqlDbType, y l mt s lit k ch nh nhng kiu ct SQL Server, nh bn s thy sau trong phn Cung cp tham s cho Command. Bng 9.8 trong phn ny trnh by nhng gi tr lit k kiu SqlDbType. Bng cch chuyn s ProviderType n SqlDbType, bn c th nhn thy tn thc ca kiu ct SQL Server.
S lp li u tin ca vng lp ngoi trnh by tt c nhng gi tr i tng DataColumn ca i tng DataRow u tin. iu ny gy ra u ra sau y s c sn xut v trnh by m hnh chi tit ca ct ProductID; ch s ProviderType v tn ch nh ProduvtID l mt kiu int SQL Server;
ColumnName = ProductID ColumnOrdinal = 0 ColumnSize = 4 NumericPrecision = 0 NumericScale = 0 IsUnique = IsKey = BaseCatalogName = BaseColumnName = ProductID BaseSchemaName = BaseTableName = DataType = System.Int32 AllowDBNull = False ProviderType = 8 ProviderType = Int IsAliased = IsExpression = IsIdentity = True IsAutoIncrement = True IsRowVersion = IsHidden = IsLong = False IsReadOnly = True ngha ca nhng kt qu ny c trnh by trong bng 8.6. Table 8.6: nhng gi tr ct biu GI TR M T ColumnName Tn ca ct. ColumnOrdinal S th t ct. Table 8.6: nhng gi tr ct biu GI TR M T ColumnSize Chiu di Cc i ( s k t) ca mt gi tr ct. Cho nhng kiu chiu di c nh SQL Server nh int, ColumnSize l di ca kiu ny. NumericPrecision Tng s lng ch s c dng i din cho mt kiu du chm ng. Mt v d v mt kiu du chm ng l kiu float SQL Server. NumericScale S tng ca nhng ch s bao gm nhng ch s v bn tri v v bn phi ca du phy s thp phn. IsUnique Gi tr Boole true/ false: ch nh liu hai hng c th c cng gi tr trong ct hin thi khng. IsKey Gi tr Boole true/false ch nh Liu ct c phi l b phn ca kha chnh. BaseCatalogName Tn ti liu trong c s d liu cha ng ct. BaseCatalogName mc nh l Null. BaseColumnName Tn ct trong c s d liu. n s khc vi ColumnName nu bn s dng mt b danh cho ct. BaseSchemaName Tn ca m hnh trong c s d liu c cha ng ct. BaseSchemaName mc nh l Null. BaseTableName Tn ca bng hay view trong c s d liu cha ct. BaseTableName mc nh l Null. DataType Kiu .NET i din cho ct. bn s hc v kiu .NET trong chng ti. AllowDBNull Gi tr Boole true/false ch nh liu c phi ct c th chp nhn mt c s d liu gi tr Null. ProviderType Ch nh kiu d liu ca ct. IsAliased Gi tr Boole true/false ch nh liu c phi tn ct l mt b danh. IsExpression Gi tr Boole true/false ch nh liu c phi ct l mt biu thc. IsIdentity Gi tr Boole true/false ch nh liu c phi ct l kha. IsAutoIncrement Gi tr Boole true/false ch nh liu c phi ct s c t ng gn mt gi tr cho mt hng mi v gi tr ny s c tng dn. IsRowVersion Gi tr Boole true/false ch nh liu c phi ct cha ng mt hng c d liu c nh c nh danh l khng th vit vo IsHidden Gi tr Boole true/false ch nh liu c phi ct c n. IsLong Gi tr Boole true/false ch nh liu c phi ct cha mt i tng long nh phn (BLOB). A BLOB cha mt chui long ca d liu nh phn. IsReadOnly Gi tr Boole true/false ch nh liu c phi ct c th sa i c.
Di y l minh ha hiu ng ca vic s dng CommandBehavior. SchemaOnly v hin th m hnh chi tit cho nhng ct ProductID, ProductName, v UnitPrice.
Listing 8.3: SCHEMAONLYCOMMANDBEHAVIOR.CS /* SchemaOnlyCommandBehavior.cs illustrates how to read a table schema */
using System; using System.Data; using System.Data.SqlClient;
class SchemaOnlyCommandBehavior { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// pass the CommandBehavior.SchemaOnly constant to the // ExecuteReader() method to get the schema SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.SchemaOnly); // read the DataTable containing the schema from the DataReader DataTable myDataTable = productsSqlDataReader.GetSchemaTable();
// display the rows and columns in the DataTable foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("\nNew column details follow:"); foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); if (myDataColumn.ToString() == "ProviderType") { Console.WriteLine(myDataColumn + "= " + ((System.Data.SqlDbType) myDataRow[myDataColumn])); } } }
Khi bn gn thuc tnh CommandType cho mt i tng Command l TableDirect, ngha l bn cho bit bn mun truy xut tt c nhng hng v ct ca mt bng c th .bn ch nh tn ca bng cn truy xut trong thuc tnh CommandText.
Ch : i tng SqlCommand khng h tr kiu Command TableDirect. Th d trong phn ny s s dng i tng OleDbCommand thay th.
Nh bn bit, bn c th s dng i tng SqlConnection kt ni vi SQL Server. Bn cng c th s dng OleDbConnection kt ni vi SQL Server. Bn n gin gn SQLOLEDB cho Provider trong string kt ni chuyn vo b khi to OleDbConnection. Th d:
OleDbConnection myOleDbConnection = new OleDbConnection( "Provider=SQLOLEDB;server=localhost;database=Northwind;" + "uid=sa;pwd=sa" );
Bn s dng phng thc ExecuteScalar() thc thi pht biu SELECT SQL tr v mt gi tr n; nhng gi tr khc b b qua. Phng thc ExecuteScalar() tr v mt gi tr n nh l mt i tng ca lp SystemObject. Mt s dng cho phng thc ExecuteScalar() s thc hin mt pht biu SELECT s dng mt chc nng tng th nh Count() ly s hng trong mt bng. NHng chc nng tng th ny s c trnh by trong chng 4, gii thu v lp trnh Transact-SQL.
Th d, pht biu sau gn cho thuc tnh CommandText ca i tng mySqlCommand mt pht biu SELECT s dng hm Count(). Pht biu ny tr v tng s hng c trong bng Products:
Tip theo, pht biu sau thc thi pht biu SELECT trn s dng phng thc ExecutetScalar() :
int returnValue = (int) mySqlCommand.ExecuteScalar();
Bn ch l ti buc kiu i tng chung c tr li t ExecuteScalar() thnh mt int trc khi lu gi kt qu vo bin int "returnValue".
Code di y minh ha cho s s dng phng thc ExecuteScalar().
Listing 8.5: EXECUTESCALAR.CS /* ExecuteScalar.cs illustrates how to use the ExecuteScalar() method to run a SELECT statement that returns a single value */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteScalar { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT COUNT(*) " + "FROM Products"; mySqlConnection.Open();
// call the ExecuteScalar() method of the SqlCommand object // to run the SELECT statement int returnValue = (int) mySqlCommand.ExecuteScalar(); Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close(); } } The output from this program is as follows: mySqlCommand.ExecuteScalar() = 79
Tt nhin, u ra ca cc bn c th thay i ph thuc vo s hng trong bng nhng sn phm ca cc bn.
THC THI MT Command TRUY XUT D LIU NH MT XML S DNG PHNG THC ExecuteXMLReader():
Bn s dng phng thc ExecuteXmlReader() thc thi mt pht biu SELECT SQL tr v d liu XML. Phng thc ExecuteXmlReader() tr v nhng kt qu trong mt i tng XmlReader, v ri sau bn s s dng n c d liu XML truy xut c.
Ch phng thc ExecuteXmlReader() ch p dng cho lp SqlCommand.
SQL Server m rng tiu chun SQL cho php bn truy vn c s d liu v ly nhng kt qu v nh XML. c bit, bn c th thm mt mnh FOR XML vo cui ca mt pht biu SELECT.Mnh FOR XML C c php nh di y:
FOR XML {RAW | AUTO | EXPLICIT} [, XMLDATA] [, ELEMENTS] [, BINARY BASE64]
Bng 8.7 trnh by s m t v nhng t kha s dng trong mnh FOR XML.
Table 8.7: Nhng t kha cho XML T Kha M t FOR XML Ch nh SQL Server s tr li nhng kt qu nh XML. RAW Ch nh mi hng trong tp hp kt qu c tr v nh mt phn t " hng" XML. Nhng gi tr ct tr thnh nhng thuc tnh ca phn t "hng". AUTO Ch nh mi hng trong tp hp kt qu c tr v nh mt phn t XML. vi tn ca bng s dng thay cho phn t chung " hng". EXPLICIT Ch nh pht biu SELECT ca cc bn ch r mi quan h cha - con, ri s c s dng bi SQL Server to ra XML vi cu trc mng li thch hp. Table 8.7: Nhng t kha cho XML T Kha M t XMLDATA Ch nh nh ngha kiu ti liu s bao gm trong XML c tr v.. ELEMENTS Ch nh nhng ct c tr v nh nhng phn t ca hng. ni cch khc, nhng ct c tr v nh nhng thuc tnh ca hng. Bn ch c th s dng chn la ny vi AUTO. BINARY BASE64 Ch nh bt k d liu nh phn no c tr v bi cu truy vn c m ha vi BASE64. Nu bn mun truy xut d liu nh phn s dng kiu RAW v EXPLICIT, ri bn phi s dng BASE64 Nh phn. Trong kiu AUTO, d liu nh phn c tr v nh mt s tham kho theo mc nh.
Bn s xem mt th d n gin v mnh FOR XML sau y, v bn s hc chi tit y v mnh ny trong chng 16, s dng s h tr XML ca SQL Server,
Th d sau y gn mt pht biu SELECT s dng mnh FOR XML AUTO cho thuc tnh CommandText ca i tng mySqlCommand. Pht biu SELECT ny tr v nm hng u tin t bng Products theo dng XML.
mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID " + "FOR XML AUTO";
Tip theo, pht biu sau y th thi mt SELECT s dng phng ExecuteXmlReader():
Ch thch, lp XmlReader c nh nghi trong khng gian tn (namepace) Sytem.Xml.
khi s c XML t i tng XmlReader, bn s dng phng thc Read(). V ri bn kim tra chc chn rng cha c ti hng cui cng- s dng thuc tnh EOF ca i tng XmlReader . EOF tr v true nu nh khng cn hng no c, ngc li n tr v false. Bn s dng phng thc ReadOuterXml() c XML thc t t i tng XmlReader.th d sau y minh ho lm th no c XML t myXmlReader:
myXmlReader.Read(); while (!myXmlReader.EOF) { Console.WriteLine(myXmlReader.ReadOuterXml()); }
Code di y minh ho cch s dng phng thc ExecuteXmlReader().
/* ExecuteXmlReader.cs illustrates how to use the ExecuteXmlReader() method to run a SELECT statement that returns XML */
using System; using System.Data; using System.Data.SqlClient; using System.Xml;
class ExecuteXmlReader { public static void Main() { SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa); SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to // a SELECT statement that retrieves XML mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + ORDER BY ProductID " + "FOR XML AUTO";
mySqlConnection.Open();
// create a SqlDataReader object and call the ExecuteReader() // method of the SqlCommand object to run the SELECT statement XmlReader myXmlReader = mySqlCommand.ExecuteXmlReader();
// read the rows from the XmlReader object using the Read() method myXmlReader.Read(); while (!myXmlReader.EOF) { Console.WriteLine(myXmlReader.ReadOuterXml()); }
myXmlReader.Close(); mySqlConnection.Close(); } } Bn s ch l ti mang vo namespace System. Xml ngay trc on code khi u ca chng trnh ny. Kt qu u ra ca chng trnh ny nh sau y <Products ProductID="1" ProductName="Chai" UnitPrice="18.0000"/> <Products ProductID="2" ProductName="Chang" UnitPrice="19.0000"/> <Products ProductID="3" ProductName="Aniseed Syrup" UnitPrice="10.0000"/> <Products ProductID="4" ProductName="Chef Anton's Cajun Seasoning" UnitPrice="22.0000"/> <Products ProductID="5" ProductName="Chef Anton's Gumbo Mix" UnitPrice="21. 3500"/>
THC THI NHNG LNH SA I THNG TIN TRONG C S D LIU:
Bn c th s dng phng thc ExecuteNonQuery() ca i tng Command th thi thc thi bt c lnh no khng tr v mt tp kt qu t c s d liu. trong phn ny, bn s hc cch s dng phng thc ExecuteNonQuery() thc thi nhng lnh s i thng tin trong c s d liu.
Bn c th s dng phng thc ExecuteNonQuery() th thi nhng pht biu SQL nh INSERT, UPDATE v DELETE. Bn cng c th s dng phng thc ExecuteNonQuery() gi th tc ni (stored procedures) Khng tr v mt gi tr, hay nhng pht biu thuc ngn ng nh ngha d liu (DDL) nh CREATE TABLE V CREATE INDEX. (DDL c trnh khi qut trong chng 3, gii thiu v ngn ng truy vn c cu trc) Bng 8.8 tng kt v phng thc ExecuteNonQuery().
Table 8.8: phng thc ExecuteNonQuery() Phng thc Kiu tr v M t ExecuteNonQuery() int dng thc hin nhng cu lnh SQL m khng tr li mt tp hp kt qu, nh nhng pht biu INSERT, UPDATE, v DELETE , nhng pht biu DDL hay nhng hm gi Sstored procedure m khng tr li mt tp hp kt qu. Gi tr int c tr li l s lng hng trong c s d liu b nh hng bi lnh, nu c.
Bn s hc cch thc hin nhng pht biu INSERT,UPDATE, hay DELETE nh th no, v lm th no thc hin nhng pht biu DDL trong mc ny. Bn s hc lm th no thc thi mt hm gi stored procedure sau trong mc" thc thi SQL Server Stored Procedure".
THC THI PHT BIU INSERT, UPDATE, V DELETE S DNG PHNG THC ExecuteNonQurery:
Hy xem, th d di y thc thi mt pht biu INSERT s dng phng thc ExecuteNonQuery(), trc tin Cn mt i tng Command:
Tip theo, bn gn pht biu INSERT cho thuc tnh CommandText ca i tng Command ca bn.th d sau y pht biu INSERT cho thuc tnh CommandText ca mySqlCommand thm mt hng vo bng Customers:
Cui cng ,bn thc thi pht biu INSERT ny s dng phng thc ExecuteNonQuery():
int numberOfRows = mySqlCommand.ExecuteNonQuery();
phng thc ny tr v mt gi tr int cho bit tng s hng b nh hng ca lnh (Command). Trong th d ny gi tr tr v l tng s hng c thm vo bng Customers, l 1 ,t mt hng c thm bi pht biu INSERT.
Hy xem tip mt v d thc thi mt pht biu UPDATE sa i hng mi va mi thm vo. Code sau y gn mt pht biu UPDATE cho thuc tnh CommandText ca mySqlCommand sa i ct CompanyName cho hng mi ny, v sau gi phng thc ExecuteNonQuery() thc thi UPDATE:
ExecuteNonQuery() li tr v 1, bi v ch c mt hng b xa bi pht biu DELETE
Lit k di y minh ha s s dng phng thc ExecuteNonQuery() thc thi pht biu INSERT, UPDATE, v DELETE trnh by trong phn trn. Chng trnh ny lm ni bt mt th tc c tn DisplayRow() n truy xut v trnh by nhng chi tit ca mt hng c ch nh trong bng Customers. DisplayRow() c s dng trong chng trnh trnh by kt qu ca nhng pht biu INSERT v UPDATE .
/* ExecuteInsertUpdateDelete.cs illustrates how to use the ExecuteNonQuery() method to run INSERT, UPDATE, and DELETE statements */
using System; using System.Data; using System.Data.SqlClient;
public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// create a SqlCommand object and set its Commandtext property // to an INSERT statement SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "INSERT INTO Customers (" + " CustomerID, CompanyName" + ") VALUES (" + " 'J2COM', 'Jason Price Corporation'" + ")";
mySqlConnection.Open();
// call the ExecuteNonQuery() method of the SqlCommand object // to run the INSERT statement int numberOfRows = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("Number of rows added = " + numberOfRows); DisplayRow(mySqlCommand, "J2COM");
// set the CommandText property of the SqlCommand object to // an UPDATE statement mySqlCommand.CommandText = "UPDATE Customers " + "SET CompanyName = 'New Company' " + "WHERE CustomerID = 'J2COM'";
// call the ExecuteNonQuery() method of the SqlCommand object // to run the UPDATE statement numberOfRows = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("Number of rows updated = " + numberOfRows); DisplayRow(mySqlCommand, "J2COM");
// set the CommandText property of the SqlCommand object to // a DELETE statement mySqlCommand.CommandText = "DELETE FROM Customers " + "WHERE CustomerID = 'J2COM'";
// call the ExecuteNonQuery() method of the SqlCommand object // to run the DELETE statement numberOfRows = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("Number of rows deleted = " + numberOfRows);
mySqlConnection.Close(); } } The output from this program is as follows: Number of rows added = 1 mySqlDataReader["CustomerID"] = J2COM mySqlDataReader["CompanyName"] = Jason Price Corporation Number of rows updated = 1 mySqlDataReader["CustomerID"] = J2COM mySqlDataReader["CompanyName"] = New Company Number of rows deleted = 1
THC THI PHT BIU DDL S DNG PHNG THCExecuteNonQuery():
Ngoi vic chy nhng pht biu INSERT, UPDATE, v DELETE, bn cng c th s dng phngthc ExecuteNonQurey() thc thi nhng pht biu DDL nh CREATE TABLE.
Hy xem xt mt th d thc thi mt pht biu CREATE TABLE, tip theo mt pht biu ALTER TABLE, theo sau l mt pht biu DROP TABLE. Trc tin cn mt i tng Command:
Tip theo bn gn pht biu CREATE TABLE cho thuc tnh CommandText ca i tng Command. Th d sau y gn mt pht biu CREATE TABLE cho thuc tnh CommandText ca i tng mySqlCommand_ to ra mt bng tn MyPersons lu tr thng tin v ngi:
Mt ln na, ExecuteNonQuery() Tr li -1 do pht biu ALTER TABLE khng nh hng n bt k hng no.
Th d cui cng thc thi mt pht biu DROP TABLE xa bng MyPersons:
mySqlCommand.CommandText = "DROP TABLE MyPersons"; result = mySqlCommand.ExecuteNonQuery();
ExecuteNonQuery() li tr v -1.
Code di y minh ha s s dng phng thc ExecuteNonQuery() thc thi nhng pht biu DDL trnh by phn trn.
/* ExecuteDDL.cs illustrates how to use the ExecuteNonQuery() method to run DDL statements */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteDDL { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// set the CommandText property of the SqlCommand object to // a CREATE TABLE statement mySqlCommand.CommandText = "CREATE TABLE MyPersons (" + " PersonID int CONSTRAINT PK_Persons PRIMARY KEY," + " FirstName nvarchar(15) NOT NULL," + " LastName nvarchar(15) NOT NULL," + " DateOfBirth datetime" + ")";
mySqlConnection.Open();
// call the ExecuteNonQuery() method of the SqlCommand object // to run the CREATE TABLE statement Console.WriteLine("Creating MyPersons table"); int result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result);
// set the CommandText property of the SqlCommand object to // an ALTER TABLE statement mySqlCommand.CommandText = "ALTER TABLE MyPersons " + "ADD EmployerID nchar(5) CONSTRAINT FK_Persons_Customers " + "REFERENCES Customers(CustomerID)";
// call the ExecuteNonQuery() method of the SqlCommand object // to run the ALTER TABLE statement Console.WriteLine("Altering MyPersons table"); result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result);
// set the CommandText property of the SqlCommand object to // a DROP TABLE statement mySqlCommand.CommandText = "DROP TABLE MyPersons";
// call the ExecuteNonQuery() method of the SqlCommand object // to run the DROP TABLE statement Console.WriteLine("Dropping MyPersons table"); result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result);
mySqlConnection.Close(); } } u ra ca chng trnh ny nh sau: Creating MyPersons table mySqlCommand.ExecuteNonQuery() = -1 Altering MyPersons table mySqlCommand.ExecuteNonQuery() = -1 Dropping MyPersons table mySqlCommand.ExecuteNonQuery() = -1
GII THIU V TRANSACTION (NHNG GIAO DCH D LIU)
Trong Chng 3, bn thy bn c th nhm nhng cu lnh SQL li cng nhau nh th no vo trong nhng giao dch. v ri Giao dch c giao ph hay hi phc nh mt n v. v d, trong trng hp mt giao dch cng vic ngn hng, bn c l mun rt tin t mt ti khon v chuyn tin t vo ti khon khc. ri bn giao ph c hai s thay i ny nh mt n v, hay nu sy ra vn , hon nguyn c hai s thay i ny. Bn s c gii thiu s dng nhng giao dch trong ADO.NET Trong mc ny. C ba lp Giao dch SqlTransaction, OleDbTransaction, V OdbcTransaction, v bn s dng mt i tng ca mt trong s nhng lp ny i din cho mt giao dch trong ADO.NET. Ti s ch cch cho bn lm sao s dng mt i tng ca lp SqlTransaction mc ny.
Chng ta hy cho mt v d v giao dch gm c hai pht biu INSERT. pht biu INSERT u tin s thm mt hng vo nhng bng Customers, v pht biu th hai s thm mt hng vo bng Orders. Hng mi trong bng Orders s tham chiu vi hng mi trong bng Customers,v hai pht biu INSERT nh di y:
INSERT INTO Orders ( CustomerID ) VALUES ( 'J3COM' ) Bn c th s dng nhng bc sau y thc hin hai s pht biu INSERT ny s dng mt i tng SqlTransaction : 1. To ra mt i tng SqlTransaction v khi ng giao dch bng cch gi Phng thc BeginTransaction() ca i tng SqlConnection. 2. To mt i tng SqlCommand gi cu lnh SQL. 3. t thuc tnh Giao dch (Transaction) cho i tng SqlCommand ti i tng SqlTransaction c to ra trong bc 1. 4. t thc tnh ComandText ca i tng SqlCommand ti pht biu INSERT u tin. Pht biu INSERT ny thm mt hng vo bng Customers. 5. Chy pht biu INSERT u tin s dng phng thc ExecuteNonQuery() ca i tng SqlCommand. Phng thc ny c s dng bi v pht biu INSERT khng tr li mt tp hp kt qu. 6. t thuc tnh CommandText ca i tng SqlCommand l pht biu INSERT th hai. Pht biu ny thm mt hng vo bng Orders. 7. chy pht biu INSERT th hai s dng ExecuteNonQuery() ca i tng SqlComand. 8. Giao ph giao dch S dng phng thc Commit() ca i tng SqlTransaction. thc thi ny to thnh hai hng mi b sung bn vng trong c s d liu bi nhng pht biu INSERT.
Danh sch 8.9 minh ha nhng bc ny.
Danh sch 8.9:EXECUTETRANSACTION.CS /* ExecuteTransaction.cs illustrates the use of a transaction */ using System; using System.Data; using System.Data.SqlClient; class ExecuteTransaction { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
mySqlConnection.Open();
// step 1: create a SqlTransaction object and start the transaction // by calling the BeginTransaction() method of the SqlConnection // object SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction();
// step 2: create a SqlCommand object to hold a SQL statement SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// step 3: set the Transaction property for the SqlCommand object mySqlCommand.Transaction = mySqlTransaction;
// step 4: set the CommandText property of the SqlCommand object to // the first INSERT statement mySqlCommand.CommandText = "INSERT INTO Customers (" + " CustomerID, CompanyName" + ") VALUES (" + " 'J3COM', 'Jason Price Corporation'" + ")";
// step 5: run the first INSERT statement Console.WriteLine("Running first INSERT statement"); mySqlCommand.ExecuteNonQuery();
// step 6: set the CommandText property of the SqlCommand object to // the second INSERT statement mySqlCommand.CommandText = "INSERT INTO Orders (" + " CustomerID" + ") VALUES (" + " 'J3COM'" + ")";
// step 7: run the second INSERT statement Console.WriteLine("Running second INSERT statement"); mySqlCommand.ExecuteNonQuery();
// step 8: commit the transaction using the Commit() method // of the SqlTransaction object Console.WriteLine("Committing transaction"); mySqlTransaction.Commit(); mySqlConnection.Close(); } }
Ch thch nu bn mun hu nhng cu lnh SQL to ra giao dch, bn c th s dng phng thc Rollback()thay cho phng thc Commit().Theo mc nh, nhng giao dch l Roolback . Lun lun s dng phng thc Commit() hay Rollback() r rng ch ra liu bn mun giao ph hay hi nguyn nhng giao dch ca cc bn.
u ra t chng trnh ny Nh i theo sau: Running first INSERT statement Running second INSERT statement Committing transaction
Nu bn mun chy chng trnh hn mt ln, bn s cn loi b hng c thm vo bng Customers v Orders s dng nhng pht biu DELETE sau (bn c th thc hin iu ny nh s dng cng c phn tch truy vn):
DELETE FROM Orders WHERE CustomerID = 'J3COM'
DELETE FROM Customers WHERE CustomerID = 'J3COM'
CUNG CP NHNG THAM S CHO COMMANDS:
Trong nhng v d bn c nhn thy trn ti im ny, nhng gi tr cho mi ct c c vit m c nh trong nhng cu lnh SQL. Chng hn, Trong Danh sch 8.9, c trnh by trc , pht biu INSERT m thm hng vo bng khch hng l:
Nh bn c th nhn thy, nhng gi tr cho nhng ct CustomerID v CompanyName c vit m c nh Ti ' J3COM ' V 'Jason Price Corporation'. Nu bn phi thc hin nhiu pht biu INSERT nh vy, nhp nhng gi tr ct bng m code s mt nhc v khng c hiu qu. May mn thay, bn c th s dng nhng tham s gii quyt vn ny. Nhng tham s cho php bn ch nh nhng gi tr ct khc nhau trong khi chy chng trnh ca cc bn.
thc hin mt lnh cha nhng tham s, bn s dng nhng bc cp cao sau y : 1. To ra mt i tng Lnh (Command) ang cha ng mt cu lnh SQL vi tham s placeholders. Placeholders (@....) ny nh du v tr ni mt tham s s c cung cp. 2. Thm nhng tham s vo i tng Lnh. 3. Gn cho nhng tham s nhng gi tr ch nh . 4. thc hin lnh (Command). Chng ta hy xem xt nhng chi tit ca bn bc khi s dng nhng tham s vi SQL Server.
BC 1: TO MT I TNG COMMAND CHA NHNG CU LNH SQL VI NHNG THAM S DA CH:
bt k ni no m bn t mt gi tr ct trong cu lnh SQL ca bn, bn ch nh mt tham s i ch (placeholder) thay vo . Mt tham s a ch (placeholder) nh du v tr ni mt gi tr s c cung cp sau . C php bn s dng cho placeholders ph thuc vo c s d liu Bn S dng. Vi my ch phc v SQL, tham s i ch ( placeholders) s l @CustomerID v @CompanyName. Pht biu INSERT sau y s dng tham s a ch ny Cho Nhng gi tr ct CustomerID, CompanyName, V ContactName ca bng khch hng:
INSERT INTO Customers CustomerID, CompanyName, ContactName ) VALUES @CustomerID, @CompanyName, @ContactName ) Bn c th s dng mt tham s a ch bt c ni u mt gi tr ct l hp l trong mt pht biu Chn la, Chn, Cp nht, hay Xa .
SELECT * FROM Customers WHERE CustomerID = @CustomerID
UPDATE Customers SET CompanyName = @CompanyName WHERE CustomerID = @CustomerID
DELETE FROM Customers WHERE CustomerID = @CustomerID
Chng ta hy xem xt ti m no m to ra mt i tng SqlCommand v gn thuc tnh CommandText ca n thnh mt pht biu INSERT:
pht biu INSERT ny s c dng thm mt hng vo bng Customers. Nhng gi tr ct cho hng ny s c ch r nh s dng nhng tham s. Mi th thc hin trong m trc y, s to ra mt i tng SqlCommand vi mt pht biu INSERT c tham s a ch. Trc khi bn c th thc hin lnh chn ny, bn cn thm nhng tham s thc ti i tng SqlCommand v bn s thc hin iu ny trong bc tip theo.
BC 2: THM NHNG THAM S VO I TNG LNH(COMMAND)
thm nhng tham s vo i tng Command ca bn, bn s dng phng thc Add().N b qu ti, v phin bn c dng trong mc ny chp nhn ba tham s: Chui tham s a ch cho tham s trong cu lnh SQL ca cc bn. Chng hn, @CustomerID l placeholder u tin trong pht biu INSERT c trnh by trong mc trc y. Kiu cho ct trong c s d liu. vi SQL Server, nhng kiu ny c nh ngha trong lp lit k System.Data.SqlDbType. Bng 8.9 trnh by nhng kiu c s d liu ny:
Bng 8.9: nhng thnh vin Lit k SqlDbType Thnh vin M t BigInt Mt s nguyn 64-bit gia -2 63 (-9,223,372,036,854,775,808) v 2 63 = (9,223,372,036,854,775,807). Binary Mt mng ca nhng byte vi chiu di cc i 8,000 phn t. Bit Mt gi tr s khng du c th l 0, 1, hay mt tham chiu null. Char Mt chui nhng k t khng phi Unicode vi chiu di cc i 8,000 k t. DateTime Mt gi tr ngy thng v thi gian gia 12: 00: 00 _ 1, thng 1 , 1753 v 11: 59: 59 PM _31,thng 12, 9999. chnh xc ti 3.33 mili-giy. Decimal gi tr s chnh xc v quy m, c nh gia-1038 + 1 (v) 1038 - 1. Float Mt s c du chm ng 64-bit gia-1.79769313486232 E308 v 1.79769313486232 E308 chnh xc vi 15 ch s c ngha . Image Mt mng ca nhng byte vi chiu di cc i 2^31 =(2,147,483,647). Int Mt S nguyn 32-bit c k mu gia-2^31 (-2,147,483,648) V 2^31 = (2,147,483,647). Money Mt gi tr tin t gia-922,337,203,685,477.5808 v 922,337,203,685,477.5807. chnh xc i vi 1/10,000 th ca mt n v tin t. NChar Mt chui ca nhng k t Unicode vi chiu di cc i 4,000 k t. Ntext Mt chui nhng k t Unicode vi Mt chiu di cc i 2^30 k t = (1,073,741,823). NVarChar Mt chui nhng k t Unicode vi Mt chiu di cc i 2^30 = (1,073,741,823). Real Mt S du chm ng 32-bit gia-3.402823 E38 v 3.402823 E38, chnh xc vi by ch s c ngha . SmallDateTime Mt gi tri ngy thng v thi gian gia 12: 00: 00 AM_ 1, thng1.1900 v 11: 59: 59 _ 6, thng 6, 2079. PM , chnh xc i vi 1 pht. SmallInt Mt S nguyn 16-bit gia-2^15 (-32,768) V 2^15 = (32,767). Thnh vin M t SmallMoney Mt gi tr tin t gia-214,748.3648 v 214,748.3647. Chnh xc i vi 1/10,000 th ca mt n v tin t. Text Mt chui nhng k t khng phi Unicode vi chiu di cc i 2^31 = (2,147,483,647). Timestamp Mt chui ngy thng v thi gian trong nh dng yyyymmddhhmmss. TinyInt mt s nguyn khng du 8-bit gia 0 v 2^8 - 1 (255). UniqueIdentifier Mt Gi tr s nguyn 128-bit (16 byte) v l duy nht ngang qua tt c cc my tnh v nhng mng. VarBinary Mt mng nhng byte vi chiu di cc i 8,000 phn t. VarChar Mt chui nhng k t khng phi Unicode vi chiu di cc i 4,000 k t. Variant Mt kiu d liu m c th cha nhng s, nhng chui, nhng byte hay nhng gi tr ngy thng. Chiu di cc i ca gi tr tham s. Bn ch nh tham s ny ch khi s dng nhng kiu di bin s, chng hn, Char v VarChar. Trc trong bc 1, thuc tnh CommandText cho mySqlCommand c ba tham s a ch placeholders v l tp hp nh sau:
Ch bn gi phng thc Add() thng qua thuc tnh Parameters ca mySqlCommand. yu cu mt vi gii thch. Mt i tng SqlCommand ct gi nhng tham s s dng Mt i tng SqlParameterCollection, v l Mt tp hp Ca nhng i tng SqlParameter (mt i tng SqlParameter cha ng nhng chi tit ca mt tham s). Mt trong s nhng phng thc ca SqlParameterCollection l Add(),v bn thng s dng thm mt i tng SqlParameter vo tp hp. Bi vy, thm mt tham s Ti mySqlCommand, Bn gi phng thc Add() thng qua thuc tnh Parameters ca n.
nh bn c th thy t m trc y l thm ba tham s n mySqlCommand, tham s @CustomerID c nh ngha nh mt NChar_ mt chui ca nhng k t Unicode vi chiu di cc i 4,000 k t. Mt gi tr ca 5 c gi i nh tham s th ba ti phng thc Add() cho @CustomerID, ngha l mt "s cc i 5 k t" c th cung cp nh gi tr tham s. Tng t, tham s @CompanyName v @ContactName c nh ngha nh mt NVarChar_ mt chui nhng k t Unicode- vi chiu di cc i tng ng 40 v 30 k t, nh ch nh bi tham s th ba ti phng thc Add(). Bn s thy s thit t ca nhng tham s ny vi nhng gi tr c th trong bc tip theo.
BUC 3: GN NHNG THAM S VI NHNG GI TR C TH:
Bn s dng thuc tnh Value ca mi tham s t n ti mt Gi tr ch nh trong i tng Lnh (Command) cc bn. Nhng gi tr ny s thay th cho tham s a ch ( placeholders) trong cu lnh SQL ca bn. V d sau y s dng thuc tnh Value t nhng Gi tr cho nhng tham s b sung Trong mc trc y:
Trong v d ny,nhng tham s @CustomerID, @CompanyName, V @ContactName c gn cc gi tr tng ng : J4COM, J4 Company, v Jason Price . Nhng gi tr ny s c th cho tham s a ch placeholders trong pht biu INSERT, tr thnh:
Nh bn c th nhn thy, nhng gi tr ct ging nh nhng gi tr c ch nh trong thuc tnh Value cho mi tham s. Bn cng c th thm mt tham s v t gi tr ca n trong cng mt bc. Chng hn:
Bn cng c th t mt tham s vi mt gi tr null. nh bn bn hc trong Chng 2, "Gii thiu v nhng c s d liu, " Mt ct nh ngha vi gi tr Null c th cha mt gi tr Null. Mt gi tr Null ch nh mt gi tr ct cha c bit. Bn ch nh mt tham s c th chp nhn mt gi tr null bng cch t thuc tnh IsNullable l true (nu false th ngc li). Chng hn:
thc thi lnh, bn s dng mt trong s nhng phng thc ca i tng Lnh (Command) . Chng hn:
mySqlCommand.ExecuteNonQuery();
m lnh ny chy pht biu INSERT thm hng mi vo bng Customers. Ti s dng phng thc ExecuteNonQuery() v mt pht biu INSERT khng tr li mt tp hp kt qu t c s d liu. Bn cng c th s dng phng php ny thc hin pht biu UPDATE v DELETE . Nu bn ang thc hin mt pht biu SELECT , bn s dng nhng phng thc ExecuteReader(), ExecuteScalar(), Hay ExecuteXmlReader() .
Danh sch 8.10 minh ha bn bc ny. Danh sch 8.10: USINGPARAMETERS.CS
/* UsingParameters.cs illustrates how to run an INSERT statement that uses parameters */
using System; using System.Data; using System.Data.SqlClient;
class UsingParameters { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// step 2: add parameters to the Command object mySqlCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5); mySqlCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40); mySqlCommand.Parameters.Add("@ContactName", SqlDbType.NVarChar, 30); // step 3: set the parameters to specified values mySqlCommand.Parameters["@CustomerID"].Value = "J4COM"; mySqlCommand.Parameters["@CompanyName"].Value = "J4 Company"; mySqlCommand.Parameters["@ContactName"].IsNullable = true; mySqlCommand.Parameters["@ContactName"].Value = DBNull.Value;
// step 4: execute the command mySqlCommand.ExecuteNonQuery(); Console.WriteLine("Successfully added row to Customers table");
mySqlConnection.Close(); } }
u ra t chng trnh ny Nh sau:
Successfully added row to Customers table
TH THI NHNG TH TC LU TR TRONG SQL Server:
Trong Chng 4, bn thy cch to v thc thi nhng th tc lu tr (stored procedures )s dng pht biu T- SQL nh th no. Trong mc ny, bn s thy cch thc thi nhng th tc lu tr SQL Server nh th no khi s dng ADO.NET. Trong Bng 8.1, c trnh by trc trong chng ny, Ti cp n CommandType ca StoredProcedure. Mc du bn c th s dng CommandType ny ch r l mt lnh(Command) s thc hin mt th tc lu tr, bn tht s tt hn t b s dng lnh(Command) thc thi T- SQL Thc hin mt th tc lu tr. y l bi v bn c th c nhng gi tr c tr v t mt th tc lu tr thng qua mt pht biu RETURN, m bn khng th lm khi t CommandType l StoredProcedure. ng thi, n lm cho m ca cc bn d hiu hn khi bn s dng EXECUTE Command.
C mt i cch m bn c th thc hin mt th tc lu tr (stored procedure) ph thuc vo th tc ca cc bn c tr li mt tp hp kt qu hay khng. ( mt tp hp kt qu l mt hoc nhiu hng c truy xut t mt bng bi mt pht biu SELECT ). Bn s hc hai cch ny thc hin mt th tc lu tr tip theo y.
THC THI MT TH TC KU TR (Stored Procedure)M KHNG TR LI MT TP HP KT QU:
Nu th tc ca cc bn khng tr li mt tp hp kt qu, th bn s dng nhng bc sau y thc hin n: 1. To mt i tng Command v gn thuc tnh CommandText vi mt pht biu thc thi (EXECUTE) cha lnh gi Procedure ca bn. 2. Thm bt k tham s c yu cu no cho lnh gi th tc vo i tng Lnh (Command ) ca bn, 3. Thc thi i tng Command ca cc bn s dng phng thc ExecuteNonQuery() . 4. c nhng gi tr ca bt k tham s u ra no.
Bn s thy cch s dng bn bc ny gi nhng th tc lu tr SQL Sever sau y nh th no: Th tc u tin, AddProduct(), s tr li mt tham s u ra c nh ngha s dng t kha OUTPUT. Th tc th hai, AddProduct2(), S tr v mt tham s u ra s dng lnh RETURN. Nhng v d ny s cho bn thy nhng cch c th thc hin mt th tc lu tr s dng ADO.NET v c nhng tham s u ra.
THC THI TH TC STORED PROCEDURE AddProduct():
Trong Chng 4, bn thy cch to ra mt th tc lu tr (Stored Procedure) trong c s d liu Northwind SQL Server. Th tc bn nhn thy c tn AddProduct(),v Danh sch 8.11 trnh by AddProduct.sql Nguyn bn, iu to ra th tc AddProduct().Bn thy cch chy nguyn bn (Script) ny nh th no Trong Chng 4. Nu bn cha chy nguyn bn (Script) ny khi cChng 4, v bn mun chy v d chng trnh C# c trnh by sau , bn s cn chy nguyn bn ny. AddProduct() Thm mt hng vo bng Products v tr li ProductID ca hng mi nh mt tham s u ra.
Danh sch 8.11: ADDPRODUCT.SQL /* AddProduct.sql To ra mt th tc thm mt hng vo bng Products s dng nhng gi tr gi qua nh nhng tham s Ti th tc. Th tc tr li ProductID ca hng mi trong mt tham s u ra c tn @MyProductID
- s dng hm SCOPE_IDENTITY() c gi tr kha chnh sau cng, c chn vo trong - - mt bng c thc hin bn trong - b phn c s d liu hin thi v th tc lu tr, - v th SCOPE_IDENTITY tr li ProductID cho hng mi trong bng Products trong trng - hp ny
SELECT @MyProductID = SCOPE_IDENTITY()
Ch tham s u ra c tn @MyProductID c tr v bi th tc lu tr AddProduct().V AddProduct() Khng tr li mt tp hp kt qu, bn s dng tp hp u tin ca nhng bc c phc tho trc . Chng ta hy kho st nhng chi tit ca bn bc ny thc thi th tc lu tr ny.
BUC 1: TO MT I TNG COMMAND V GN THUC TNH CommandText CA N VI PHT BIU EXECUTE
Bc u tin ca bn l to ra mt i tng Command v t thuc tnh CommandText ca n vi mt pht biu EXECUTE c cha lnh gi ti th tc lu tr AddProduct();ch tham s a ch placeholders thng nh du v tr ni nhng gi tr tham s s c thay th trong bc 2
Ch tham s a ch (placeholder) u ra c tn @MyProductID. n c dng ct gi tham s u ra c tr v bi th tc lu tr AddProduct(), nhng tham s a ch (placeholders) khc c dng gi nhng gi tr ti th tc lu tr AddProduct(), v th tc ny s s dng nhng gi tr trong pht biu INSERT .
BC 2: THM BT K THAM S CN THIT NO V I TNG COMMAND:
Bc th hai ca bn l thm bt k tham s no vo i tng Command ca cc bn, nh t thuc tnh phng hng (Direction) cho bt k tham s u ra no thnh ParameterDirection.Output.
Trong v d ny, th tc lu tr AddProduct() ch i mt tham s u ra ct gi mt ga tr ProductID cho hng mi, v do bn cn thm mt tham s u ra vo i tng Lnh (Command) ca bn. Bn thc hin iu ny bi s thit t thuc tnh phng hng Direction ca tham s ca bn thnh ParameterDirection.Output. th d :
Ch nhng kiu tham s SqlDbType tng ng ti nhng kiu c ch i bi th tc lu tr AddProduct().Nhng gi tr, nhng tham s c t ra ri c th cho placeholders trong thc thi pht biu c c trnh by trong bc 1.
BC 3: THC THI I TNG LNH(COMMAND) S DNG PHNG THC ExecuteNonQuery()
Bc th ba ca bn l thc thi i tng Lnh (Command) ca bn s dng phng thc ExecuteNonQuery(). Bn s dng ExecuteNonQuery() V Th tc AddProduct() khng tr li mt tp hp kt qu. Chng hn:
mySqlCommand.ExecuteNonQuery();
BC 4: C NHNG GI TR CA BT K THAM S U RA NO:
Bc cui cng ca) bn l c nhng gi tr ca bt k tham s u ra no. th tc lu tr AddProduct() s dng mt tham s u ra c tn @MyProductID. Bn c gi tr tr v ny t thuc tnh Value ca @MyProductID:
m lnh ny s hin th nhng gi tr ca ProductID pht sinh bi SQL Server cho hng mi trong bng Products.
Danh sch 8.12 minh ha nhng bc gi th tc lu tr AddProduct() ny .
Danh sch 8.12: EXECUTEADDPRODUCT.CS
/* ExecuteAddProduct.cs illustrates how to call the SQL Server AddProduct() stored procedure */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteAddProduct { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); mySqlConnection.Open();
// step 1: create a Command object and set its CommandText // property to an EXECUTE statement containing the stored // procedure call SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "EXECUTE AddProduct @MyProductID OUTPUT, @MyProductName, " + "@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " + "@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " + "@MyReorderLevel, @MyDiscontinued";
// step 3: execute the Command object using the // ExecuteNonQuery() method mySqlCommand.ExecuteNonQuery();
// step 4: read the value of the output parameter Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);
mySqlConnection.Close(); } }
u ra t chng trnh ny Nh sau: New ProductID = 81
Tt nhin, ph thuc vo nhng hng hin hu trong bng Products ca cc bn, bn s c mt kt qu khc.
THC THI TH TC LU TR AddProduct2()
Nh bn s thy, Th tc lu tr AddProduct2() cng tng t nh AddProduct()ch c iu n s dng mt pht biu RETURN thay v mt tham s u ra tr v ProductID cho hng mi. Danh sch 8.13 trnh by Nguyn bn (Script)AddProduct2.sql n to ra th tc AddProduct2(). Bn s cn chy nguyn bn (Script) ny trc khi chy chng trnh C# .
Danh sch 8.13: ADDPRODUCT2. SQL
/* AddProduct2.sql To ra mt th tc thm mt hng vo bng Products s dng nhng gi tr gi qua nh nhng tham s ti th tc. Th tc tr v ProductID ca hng mi s dng mt pht biu RETURN. */
- khai bo bin @MyProductID DECLARE @MyProductID int
- chn mt hng vo trong bng sn phm INSERT INTO Products ( ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued ) VALUES ( @MyProductName, @MySupplierID, @MyCategoryID, @MyQuantityPerUnit, @MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, @MyReorderLevel, @MyDiscontinued )
- s dng hm SCOPE_IDENTITY() ly gi tr kha chnh sau cng c chn vo trong -mt bng c thc hin bn trong b phn c s d liu hin thi v th tc lu tr, - v vy SCOPE_IDENTITY tr v ProductID cho hng mi - trong bng Products trong trng hp ny
SET @MyProductID = SCOPE_IDENTITY()
RETURN @MyProductID
Ch pht biu RETURN cui tr v @MyProductID.V AddProduct2() khng tr v mt tp hp kt qu ca nhng hng, bn s dng tng t nh bn bc c trnh by trong mc trc thc hin th tc lu tr s dng ADO.NET. S khc nhau duy nht trong cu trc ca lnh EXECUTE ca bn l t thuc tnh CommandText trong bc 1. gi AddProduct2() bn t thuc tnh CommandText ca i tng Lnh(command) ca bn nh sau:
Ch n s thay i v tr ca tham s @MyProductID: n c chuyn n ngay sau t kha EXECUTE v t du bng ti gi tr tr v bi AddProduct2().S thay i ny c lm v Add- Product2() s dng mt pht biu RETURN xut tr v gi tr @MyProductID. Phn cn li ca m C# c yu cu gi AddProduct2() cng tng t nh trnh by trc trong Danh sch 8.12.
Ghi ch v ch EXECUTE l khc nhau, Ti b qua chng trnh gi AddProduct2() trong sch ny. Bn c th thy chng trnh ny trong File ExecuteAddProduct2.cs m ti cung cp. hy thoi mi chy th v kho st n.
THC THI MT TH TC LU TR (Stored Procedure) M TR V MT TP HP KT QU:
Nu th tc ca bn thuc lai tr v mt tp kt qu, th bn s dng nhng bc sau thc thi: 1. To ra mt i tng Command v gn thuc tnh CommandText ca n ti mt pht biu EXECUTE c cha hm gi th tc ca bn. 2. thm bt k tham s yu cu no vo i tng Command ca bn, nh gn thuc tnh Direction cho bt k tham s u ra no vi ParameterDirection.Output. 3. thc thi Command ca bn s dng phng thc ExecuteReader(),lu gi i tng DataReader c tr v. 4. c nhng hng trong tp hp kt qu s dng i tng DataReader ca bn. 5. ng i tong DataReader ca bn. bn phi thc hin iu ny trc khi bn c th c bt k tham s u ra no. 6. c cc tham s u ra (output parameters).
Trong v d sau y, bn s thy mt th tc lu tr c tn AddProduct3() n s tr li mt tp hp kt qu cng vi mt tham s u ra s dng mt pht biu RETURN.
Th tc AddProduct3() cng tng t nh AddProduct2(), ngai tr n cng tr li mt tp hp kt qu s dng mt pht biu SELECT. pht biu SELECT ny cha nhng ct ProductName v UnitPrice cho hng mi thm vo bng Products. Ngoi ra tp hp kt qu ny cn tr v ProductID ca hng mi bi pht biu RETURN, Danh sch 8.14 trnh by Nguyn bn (Script) AddProduct3.sql v script ny to ra Th tc AddProduct3() . Bn cn chy nguyn bn ny trc khi chy c chng trnh C#.
Danh sch 8.14: ADDPRODUCT3. SQL
/* AddProduct3.sql creates a procedure that adds a row to the Products table using values passed as parameters to the procedure. The procedure returns the ProductID of the new row using a RETURN statement and returns a result set containing the new row */
- declare the @MyProductID variable DECLARE @MyProductID int
- insert a row into the Products table INSERT INTO Products ( ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued ) VALUES ( @MyProductName, @MySupplierID, @MyCategoryID, @MyQuantityPerUnit, @MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, @MyReorderLevel, @MyDiscontinued )
- use the SCOPE_IDENTITY() function to get the last - identity value inserted into a table performed within - the current database session and stored procedure, - so SCOPE_IDENTITY returns the ProductID for the new row - in the Products table in this case SET @MyProductID = SCOPE_IDENTITY()
- return the result set SELECT ProductName, UnitPrice FROM Products WHERE ProductID = @MyProductID
- return @MyProductID RETURN @MyProductID
Do bn thy nhng c s cho m thc thi su bc c trnh by trc trong mc ny, Ti s i thng ti m vi gii thch s lc. Danh sch 8.15 trnh by chng trnh gi AddProduct3().Nhng th quan trng cn ch :
Danh sch 8.15: EXECUTEADDPRODUCT3. CS
/* ExecuteAddProduct3.cs illustrates how to call the SQL Server AddProduct3() stored procedure */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteAddProduct3 { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); mySqlConnection.Open();
// step 1: create a Command object and set its CommandText // property to an EXECUTE statement containing the stored // procedure call SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "EXECUTE @MyProductID = AddProduct3 @MyProductName, " + "@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " + "@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " + "@MyReorderLevel, @MyDiscontinued";
// step 3: execute the Command object using the ExecuteReader() // method SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
// step 4: read the rows using the DataReader object while (mySqlDataReader.Read()) { Console.WriteLine("mySqlDataReader[\" ProductName\"] = " + mySqlDataReader["ProductName"]); Console.WriteLine("mySqlDataReader[\" UnitPrice\"] = " + mySqlDataReader["UnitPrice"]); }
// step 5: close the DataReader object mySqlDataReader.Close();
// step 6: read the value of the output parameter Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);
mySqlConnection.Close(); } }
Phng thc ExecuteReader() c dng tr li tp hp kt qu cha nhng ct ProductName v UnitPrice cho hng mi. Tp hp kt qu ri s c c s dng mt i tng SqlDataReader. i tng SqlDataReader c ng trc khi c th c c tham s u ra.
u ra t chng trnh ny nh sau:
mySqlDataReader["ProductName"] = Widget mySqlDataReader["UnitPrice"] = 5.99 New ProductID = 83
TO MT I TNG COMMAND S DNG VISUAL STUDIO.NET
to ra mt i tng SqlCommand s dng Visual Studio.NET (VS.NET), bn ko mt i tng SqlCommand t tab Data ca Toolbox vo form bn. Bn c th cng ko mt i tng OleDbCommand t tab Data ca Toolbox n form ca bn.
Trc khi bn thc hin th tc c gii thch trong mc ny, thc hin cc bc sau: 1. to mt chng trnh mi tn MyDataReader cha mt trnh ng dng Windows. 2 thm mt i tng SqlConnection vo chng trnh (quay tr li chng trc y xem cch thm mt i tng SqlConnection s dng VS.NET) i tng ny s c tn mc nh l SqlConnection1. 3. nh hnh i tng sqlConnection1 ca bn truy nhp c s d liu Northwind ca bn.
Ko mt i tng SqlCommand vo form ca bn. Hnh 8.1 cho thy mt form vi mt i tng SqlCommand. i tng ny c gn tn mc nh l sqlCommand1.
Hnh 8.1: Mt i tng SqlCommand trong Mt form
sau Bn t thuc tnh Kt ni (Connection ) cho sqlCommand1 s dng danh sch th xung (dropdown list) bn phi ca thuc tnh connection trong ca s thuc tnh (property window). Bn c th la chn mt i tng kt ni(Connection) hin hu trong danh sch th xung; bn c th cng to ra mt i tng Connection mi bi la chn New t danh sch. Cho v d ny, chn i tng sqlConnection1 hin hu cho thuc tnh Connection ca i tng sqlCommand1, nh trnh by trong hnh 8.1
Bn c th s dng trnh to truy vn (Query Builder) to mt cu lnh SQL bi vic kch vo nt "..." bn phi ca thuc tnh CommandText, v bn c th gn nhng tham s cho mt lnh (Command) bi vic kch nt "..." bn tri ca nhng thuc tnh tham s. Bn s gn thuc tnh CommandText ca i tng SqlCommand ca bn n mt pht biu SELECT truy xut cc ct CustomerID, CompanyName, and ContactName t bng Customers, Bn s xy dng pht biu SELECT ny s dng trnh to Query. bt u, kch nt "..." bn phi ca thuc tnh CommandText cho i tng SqlCommand ca cc bn.
Trong hp thai Add Table, chn bng Customers, nh trnh by trong hnh 8.2. click nt Add thm bng Customers vo query ca bn. click nut close tip tc.
Hnh 8.2: thm bng Customers vo truy vn s dng hp thai Add Table
Tip theo, bn xy dng truy vn ca bn s dng trnh xy dng truy vn (Query Builder). Bn la chn nhng ct Bn mun truy xut y. Thm nhng ct CustomerID, CompanyName, v ContactName s dng trnhxy dng truy vn (Query Builder), nh Hnh 8.3.
Hnh 8.3: Thm nhng ct CustomerID, CompanyName, v ContactName vo truy vn s dng Query Builder.
Kch nt Ok tip tc. Thuc tnh CommandText ca i tng SqlCommand ca bn c gn bng pht biu SELECT bn to ra trong Query Builder.
Ghi ch lu d n MyDataReader ca bn bng cch chn File - Save All. Bn s thy s s dng i tng SqlCommand Bn thm vo d n ca bn trong chng k tip.
TM TT:
Trong chng ny, bn hc cch thc hin nhng lnh c s d liu nh th no. C ba lp Lnh SqlCommand, OleDbCommand, V OdbcCommand. Bn s dng mt i tng Command thc hin mt pht biu SQL SELECT, INSERT, UPDATE, hay DELETE . Bn c th cng s dng mt i tng Command thc hin mt s gi th tc lu tr( Stored Procedure), hay truy xut tt c nhng hng v nhng ct t mt bng c th; n c bit nh mt TableDirect Command. Bn s dng mt i tng ca lp SqlCommand thc hin mt lnh truy nhp mt c s d liu SQL Server, mt i tng ca lp SqlDataReader c nhng hng truy xut c t mt c s d liu SQL Server, v mt i tng ca lp SqlTransaction i din cho mt giao dch c s d liu trong mt c s d liu SQL Server.
Trong chng k tip, bn s hc nhng chi tit ca nhng i tng DataReader.
CHNG 9: S DNG NHNG I TNG DATAREADER C NHNG KT QU
TNG QUAN:
c nhng hng s dng mt i tng DataReader (i khi c bit n nh mt con tr firehose) in hnh nhanh chng hn hn c t mt Dataset. Nhng i tng DataReader l b phn ca nhng trnh cung cp c qun l, v c ba lp DataReader: SqlDataReader, OleDbDataReader, v OdbcDataReader. Bn s dng mt i tng DataReader c nhng hng truy xut c t c s d liu s dng mt i tng Command.
Nhng i tng DataReader c th c s dng c nhng hng ch theo mt hng xui. Nhng i tng DataReader ng vai nh mt gii php i vi mt i tng Dataset (Nhng i tng Dataset cho php bn lu tr mt bn sao ca nhng hng t c s d liu, v bn c th lm vic vi bn sao ny trong khi ngt kt ni vi c s d liu) Bn khng th s dng mt DataReader sa i nhng hng trong c s d liu.
Nhng im chinh trong chng ny:
Lp SqlDataReader To mt i tng SqlDataReader c nhng hng t mt i tng SqlDataReader Tr v nhng gi tr nh kiu mnh ca ct c nhng gi tr Null Thc hin nhiu cu lnh SQL S dng mt i tng DataReader trong Visual Studio.NET
LP SQLDATAREADER:
Bn s dng mt i tng ca lp SqlDataReader c nhng hng c truy xut t mt c s d liu may ch phc v SQL, mt i tng ca lp OleDbDataReader c nhng hng t bt k c s d liu no h tr OLE DB, nh Oracle hay Access, v mt i tng ca lp OdbcDataReader c nhng hang t bt k c s d liu no h tr ODBC. Bng 9.1 cho thy mt s thuc tnh SqlDataReader.
Bng 9.1: nhng thuc tnh SqlDataReader
Thuc tnh Kiu M t Depth int Gi mt gi tr ch nh chiu su ca s lng nhau cho hng hin thi. FieldCount int Gi s ct trong hng hin thi. Thuc tnh Kiu M t IsClosed bool Gi mt gi tr bool ch nh liu i tng c d liu c ng. RecordsAffected int Gi s lng hng c thm vo, c sa i, hay c loi b bi s thc hin ca cu lnh SQL.
Ghi ch mc du lp SqlDataReader c dnh ring cho SQL SErver, rt nhiu thuc tnh v nhng phng thc trong lp ny cng tng t nh cy trong lp OleDbDataReader v lp OdbcDataReader.
Bng 9.2 cho thy mt s phng thc dng chung trong SqlDataReader .
Bng 9.2: nhng phng thc ca t SqlDataReader Phng thc Gi tr tr v M t GetBoolean() bool Tr li gi tr ca ct c ch r nh mt gi tr bool. GetByte() byte Tr li gi tr ca ct c ch r nh mt Byte. GetBytes() long c mt lung ca nhng gi tr byte t ct c ch nh vo trong mt mng byte. Gi tr di c tr li l s ca nhng gi tr byte c c t ct. GetChar() char Tr li gi tr ca ct c ch r nh mt char. GetChars() long c mt lung ca nhng gi tr char t ct c ch nh vo trong mt mng char. Gi tr di c tr li l s ca nhng gi tr char c t ct. GetDataTypeName() string tr v tn ca kiu d liu ngun cho ct c ch nh. GetDateTime() DateTime Tr li gi tr ca ct c ch r l mt kiu DateTime. GetDecimal() decimal Tr li gi tr ca ct c ch nh nh mt s thp phn. GetDouble() double Tr li gi tr ca ct c ch r nh mt double. GetFieldType() Type Tr li kiu ca ct c ch nh. GetFloat() float Tr li gi tr ca ct c ch nh nh mt float. GetGuid() Guid tr v gi tr ca ct c ch nh nh mt kha chnh duy nht tan cc (GUID). GetInt16() short Tr li gi tr ca ct c ch r nh mt short. GetInt32() int Tr li gi tr ca ct c ch r nh mt int. GetInt64() long Tr li gi tr ca ct c ch nh nh mt long. GetName() string Tr li tn ca ct c ch r. GetOrdinal() int Tr li v tr s, hay s th t, ca ct c ch nh (ct u tin c mt s th t l 0). GetSchemaTable() DataTable Tr li mt DataTable cha ng nhng chi tit ca nhng ct c ct gi trong i tng c d liu. GetSqlBinary() SqlBinary Tr li gi tr ca ct c ch r nh mt i tng SqlBinary. Lp SqlBinary c khai bo trong khng gian tn (namespace) System.Data.SqlTypes . Tt c nhng phng thc GetSql* c ch nh cho lp SqlDataReader. GetSqlBoolean() SqlBoolean Tr li gi tr ca ct c ch r nh mt i tng SqlBoolean. GetSqlByte() SqlByte Tr li gi tr ca ct c ch r nh mt i tng SqlByte. GetSqlDateTime() SqlDateTime Tr li gi tr ca ct c ch r nh mt i tng SqlDateTime. GetSqlDecimal() SqlDecimal Tr li gi tr ca ct c ch r nh mt i tng SqlDecimal. Phng thc Gi tr tr v M t GetSqlDouble() SqlDouble Tr li gi tr ca ct c ch r nh mt i tng SqlDouble. GetSqlGuid() SqlGuid Tr li gi tr ca ct c ch r nh mt i tng SqlGuid. GetSqlInt16() SqlInt16 Tr li gi tr ca ct c ch r nh mt i tng SqlInt16. GetSqlInt32() SqlInt32 Tr li gi tr ca ct c ch r nh mt i tng SqlInt32 GetSqlInt64() SqlInt64 Tr li gi tr ca ct c ch r nh mt i tng SqlInt64 GetSqlMoney() SqlMoney Tr li gi tr ca ct c ch r nh mt i tng SqlMonney. GetSqlSingle() SqlSingle Tr li gi tr ca ct c ch r nh mt i tng SqlSingle. GetSqlString() SqlString Tr li gi tr ca ct c ch r nh mt i tng SqlString. GetSqlValue() object Tr li gi tr ca ct c ch r nh mt i tng. GetSqlValues() int Sao chp gi tr ca tt c nhng ct trong hng hin thi vo trong mt i tng mng c ch nh. Tr s Int tr v bi phng thc ny l s phn t c trong mng. GetString() string Tr li gi tr ca ct c ch r nh mt chui. GetValue() object Tr li gi tr ca ct c ch r nh mt i tng. GetValues() int Sao chp gi tr ca tt c nhng ct trong hng hin thi vo trong mt i tng mng c ch nh. Tr s Int tr v bi phng thc ny l s phn t c trong mng. IsDBNull() bool Tr li mt gi tr Bool cho bit liu c phi ct ch nh cha mt gi tr null. NextResult() bool Di chuyn i tng c d liu ti hng k tip trong tp hp kt qu. Gi tr Bool tr v bi phng thc ny cho bit liu c phi cn c hng tip trong tp hp kt qu. Read() bool Di chuyn i tng c d liu ti hng k tip trong tp hp kt qu v c hng. Gi tr Bool tr v bi phng thc ny cho bit liu c phi cn c nhiu hng hn trong tp hp kt qu.
Ghi nh nhng chi tit ct DataTable bao gm tn (tn ct c lu tr trong ColumnName ca DataTable c tr li), s th t (c ct gi ColumnOrdinal), chiu di cc i ca gi tr c ct gi trong ct (c ct gi trong ColumnSize), s chnh xc v quy m ca mt ct s (c ct gi trong NumericPrecision v NumericScale), ngoi ra. S Chnh xc l s tng ca nhng ch s to ra mt s, v quy m l s tng ca nhng ch s v bn phi du phy s thp phn. Bn thy cch c mt m hnh s dng mt chng trnh trong chng trc y.
Mo nh: Khng gian tn System.Data.SqlTypes cung cp nhng lp cho nhng kiu d liu bn ng c dng bn trong SQL server. Nhng lp ny cung cp mt gii php nhanh chng hn v an ton hn cho nhng kiu d liu khc c tr v bi nhng phng thc Get*. S dng nhng lp trong namespace ny gip ngn nga nhng li do s chuyn i kiu gy ra s mt chnh xc. Bi v nhng kiu d liu khc c chuyn i xui ngc ti SqlTypes pha sau, r rng vic to ra v s dng nhng i tng bn trong namespace ny khin cho m thc thi nhanh chng hn hn na. Bn s hc nhiu hn v namespace SqlTypes sau Trong Mc " S dng nhng phng thc GetSql* c nhng gi tr Ct ".
TO MT I TNG SQLDATAREADER:
Bn c th to ra mt i tng DataReader vi cch duy nht l gi phng thc ExecuteReader() ca i tng Command. Nhng i tng Command c trnh by trong chng trc. th d, code sau y to nhng i tng cn thit v thc thi mt pht biu SELECT truy xut nm hng u tin t bng Product ca c s d liu SQL Server Northwind, lu gi nhng hng c tr v trong mt i tng SqlDataReader:
Ch i tng SqlDataReader tr v bi phng thc ExecuteReader() c ct gi trong i tng productsSqlDataReader. Bn s hc cch s dng productsSqlDataReader nh th no trong mc sau y.
C NHNG HNG T MT I TNG SQLDATAREADER
Bn c nhng hng t mt i tng DataReader s dng phng php Read() . Phng php ny tr li gi tr true (Bool) khi c hng khc c, ngc li tr v false.
Bn c th c mt gi tr ct ring l trong mt hng t mt DataReader bi s gi qua tn ca ct trong cp ngoc vung. v d, c ct CustomerID, bn s dng productsSqlDataReader[ " ProductID"]. Bn c th cng ch r ct bn mun c bng cch gi qua mt gi tr s trong du ngoc vung. Chng hn, productsSqlDataReader[0] Cng tr v gi tr ct ProductID.
Mo nh: s khc nhau gia hai cch c gi tr mt ct s thc hin: s dng con s ch nhng v tr ct thay v nhng tn ct dn n s thc hin nhanh chng hn ca m. Chng ta hy xem xt hai an m minh ha hai cch c gi tr ct ny. on m u tin s dng nhng tn ct c gi tr ct .
while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader["ProductID"]); Console.WriteLine(productsSqlDataReader["ProductName"]); Console.WriteLine(productsSqlDataReader["UnitPrice"]); Console.WriteLine(productsSqlDataReader["Discontinued"]); }
Mc d on m th hai nhanh chng hn .nhng n t linh hot hn v bn phi vit m cng nhng s ct v tr. Nu nhng v tr ct trong pht biu SELECT c thay i, bn cn thay i m cng v tr ct -v y l mt cn c mng bo tr. ng thi, s m ha cng v tr ct lm nhng chng trnh ca cc bn kh c hn.
C mt gii php cho vn ny: bn c th gi phng thc GetOrdinal() ca i tng DataReader. phng thc GetOrdinal() tr li v tr ca mt ct c tn c a vo nh mt tham s; v tr ny c bit nh th t ct . Bn c th ri s dng v tr c tr v bi GetOrdinal() truy xut nhng gi tr ct t DataReader ca cc bn.
Chng ta hy xem xt on m s dng phng thc GetOrdinal() truy xut v tr ca nhng ct trong pht biu v d SELECT sau:
int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID"); int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName"); int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice"); int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");
V bn c th s dng nhng gi tr int ny truy xut nhng gi tr ct t i tng productsSqlDataReader:
while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader[productIDColPos]); Console.WriteLine(productsSqlDataReader[productNameColPos]); Console.WriteLine(productsSqlDataReader[unitPriceColPos]); Console.WriteLine(productsSqlDataReader[discontinuedColPos]); }
Cch ny cho bn nhng u im ca c hai phng n trn : s thc hin v tnh linh hot cao.
Cnh bo: Khi bn kt thc c nhng hng t i tng DataReader ca bn, hy ng n bng phng thc Close().L do l mt i tng DataReader ang tri buc i tng Kt ni ny, v nhng lnh khc(Command) khng th c thc hin khi c mt DataReader ang m v gi kt ni ny( i tng Connection). V d sau y ng productsSqlDataReader s dng phng thc Close() .
productsSqlDataReader.Close();
Mt khi bn ng DataReader ca bn, Bn c th thc hin nhng lnh(Command) khc s dng i tng Kt ni (Connection)ca bn.
Lit k 9.1 nhng v d v s dng m c trnh by trong mc ny.
Danh sch 9.1: USINGCOLUMNORDINALS.CS /* UsingColumnOrdinals.cs illustrates how to use the GetOrdinal() method of a DataReader object to get the numeric positions of a column */
using System; using System.Data; using System.Data.SqlClient;
class UsingColumnOrdinals { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// s dng phng thc GetOrdinal() ca i tng DataReader // ly s ch v tr ca ct int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID"); int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName"); int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice"); int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock"); int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");
n lc ny, bn truy xut nhng gi tr ct t ch mt DataReader nh nhng i tng chung ca lp System.Object (nhng i tng thng c tham chiu ti nh mt hin thn ca kiu i tng C#).
Ghi ch: Tt c cc lp trong C# u c dn xut t lp System.Object.
Ti s vit li vng lp "while" c trnh by trong v d Trong mc trc y cho thy cch bn ct gi nhng gi tr ct nh nhng i tng ca lp System.Object nh th no:
Console.WriteLine("productID = " + productID); Console.WriteLine("productName = " + productName); Console.WriteLine("unitPrice = " + unitPrice); Console.WriteLine("unitsInStock = " + unitsInStock); Console.WriteLine("discontinued = " + discontinued); } on m ny dn n kt qu u ra ging nh trong Danh sch 9.1 trn. Tt c nhng g ti trnh by trong danh sch 9.1 l thuyt minh r rng mt DataReader tr v mt gi tr ct nh mt i tng ca lp System.Object theo mc nh. Khi mt i tng ca lp System.Object c trnh by bi phng thc Console.WriteLine(),trc tin i tng phi c tuyt i chuyn i thnh mt chui v sau mi trnh by.
Nh th s tt ch trnh by nhng gi tr ct, nhng s th no nu nh bn mun thc hin vi kiu tnh ton no vi mt gi tr? lm iu ny, trc tin bn phi p kiu gi tr Ti mt kiu c th. V d sau y p kiu i tng unitPrice ti mt s thp phn (decimal) v sau nhn n vi 1.2
Ghi ch Bn thm m vo cui ca mt s k t ch bo n thc kiu thp phn.
Nhng cng vic p mt i tng ti mt kiu c th, nhng n khng c thanh lch lm. N cng chng li mt trong nhng li ch chnh ca mt ngn ng lp trnh hin i: s s dng s nh kiu mnh. s nh kiu mnh c ngha l bn chn ng kiu ca mt bin hay i tng khi khai bo n. Li ch chnh ca s nh kiu mnh l bn t c kh nng c nhng li trong thi gian chy (runtime) nhng chng trnh ca bn gy ra bi vic s dng kiu sai. y l nh trnh bin tp kim tra m ca bn chc chn rng ng cnh ca kiu l ng. iu cui cng l bn nn c gng chn cho tt c nhng bin v nhng i tng ca bn vi kiu thch hp , v ch s dng p kiu khi bn khng cn s la chn khc. Trong trng hp ny, bn c mt s la chn: thay v vic p kiu, bn c th s dng mt trong nhng phng thc Get* ca i tng DataReader ly mt gi tr ct vi mt kiu thch hp.
Ghi ch Ti s dng du sao trong Get* ch bo c nhiu phng thc bt u vi Get. Bn c th xem tt c phng thc Get* trong Bng 9.2, trnh by trong mc trc.
V d , mt trong nhng phng thc Get* l GetInt32(), s tr li mt gi tr ct nh mtgi tr int. int productID = productsSqlDataReader.GetInt32(productIDColPos); Nh bn c th thy, bn xem qua s th t ca ct m c gi tr bn mun thu c ti phng thc Get*. Bn thy cch ly gi tr th t ca ct nh th no trong mc trc y.
S DNG NHNG PHNG THC Get*() C NHNG GI TR CT:
Trc khi ti trnh by bn nhng phng thc Get*() c nhng gi tr ct, bn cn bit nhng kiu C# tiu chun v nhng gi tr m chng h tr. Bn cn bit nhng iu ny nh bn c th hiu nhng kiu tng thch gia C# v SQL Server trnhby sau. Bng 9.3 trnh by nhng kiu C# tiu chun , cng vi kiu .NET v nhng gi tr c th c ct gi trong kiu C#.
Bng 9.3: Nhng kiu C# Tiu chun V. .NET
KIU C# KIU .NET NHNG GI TR bool Boolean Mt gi tr boolean true hoc false. byte Byte mt s nguyn khng du 8 bit gia 0 v 2 8 (255). char Char Mt k t Unicode 16 bit. DateTime DateTime Mt ngy thng v thi gian gia 12: 00: 00 AM Thng ging 1, 0001 v 11: 59 59 Thng mi hai 31, 9999. PM decimal Decimal Mt s chnh xc v quy m c nh gia khang + /- 1.0* 10-28 V + /- 7.9* 10-28 vi 28 ch s c ngha ca chnh xc. double Double Mt s du chm ng 64-bit gia xp x+ /- 5* 10^-324 V + /- 1.7* 10^308 vi 15 ti 16 ch s c ngha ca chnh xc. float Single Mt s du chm ng 32-bit gia xp x + /- 1.5* 10^-45 v + /- 3.4* 10^38 vi 7 ch s c ngha ca chnh xc. Guid Guid Mt gi tr s nguyn khng du 128-bit (16 byte) m l duy nht ngang qua tt c cc my tnh v nhng mng. int Int32 Mt s nguyn 32 bit gia -2 31 (-2,147,483,648) and 2 31 - 1 (2,147,483,647). long Int64 Mt s nguyn 64 bit gia -2 63 (-9,223,372,036,854,775,808) and 2 63 - 1 (9,223,372,036,854,775,807). sbyte SByte Mt s nguyn 8 bit gia -2 7 (-128) and 2 7 - 1 (127). short Int16 Mt s nguyn 16 bit gia -2 15 (-32,768) and 2 15 - 1 (32,767). string String Mt chui di -bin ca nhng k t Unicode16-bit. uint UInt32 Mt s nguyn khng du 32-bit gia 0 V 2 32 - 1 (4,294,967,295). ulong UInt64 Mt s nguyn khng du 64-bit gia 0 V 2 64 - 1 (18,446,744,073,709,551,615). ushort UInt16 Mt s nguyn khng du16-bit gia 0 V 2 16 - 1 (65,535).
Bng 9.4 trnh by nhng kiu d liu SQL Server, nhng kiu C# tiu chun thch hp, v mi phng thc DataReader Get*() tr v mi kiu C#. Bn s dng bng ny chn ra phng thc no truy xut mt kiu ct c th. Chng hn, nu bn cn ly gi tr ca mt ct bigint(s nguyn ln), bn gi phng thc GetInt64() tr v mt gi tr long. Table 9.4: NHNG KIU SQL SERVER, KIU C# TIU CHUN THCH HP, V PHNG THC GET* KIU SQL SERVER KIU C# TIU CHUN PHNG THC GET* () binary byte[] GetBytes() bigint long GetInt64() bit bool GetBoolean() char string GetString() datetime DateTime GetDateTime() decimal decimal GetDecimal() float double GetDouble() image byte[] GetBytes() int int GetInt32() money decimal GetDecimal() nchar string GetString() ntext string GetString() nvarchar string GetString() numeric decimal GetDecimal() real float GetFloat() smalldatetime DateTime GetDateTime() smallint short GetInt16() smallmoney decimal GetDecimal() sql_varient object GetValue() text string GetString() timestamp byte[] GetBytes() tinyint byte GetByte() varbinary byte[] GetBytes() varchar string GetString() uniqueidentifier Guid GetGuid()
Ghi ch Bn c th xem nhng kiu d liu SQL Server v nhng gi tr c h tr bi nhng kiu ny trong Bng 2.3 ca Chng 2," Gii thiu v nhng c s d liu." Ghi ch Nhng phng thc Get* c nh ngha trong tt c nhng lp DataReader v lm vic cho tt c cc c s d liu. Tip theo bn s thy cch s dng mt s nhng phng thc trnh by trong bng trn Bng 9.4.
MT TH D V S S DNG NHNG PHNG THC Get*():
Chng ta hy xem xt mt v d c nhng ct ProductID,ProductName, UnitPrice, UnitsInStock, t bng Products s dng nhng phng thc Get*() . hnh dung ra phi s dng phng thc Get*() no truy xut mt kiu d liu ct SQL Server c th , bn s dng Bng 9.4, c trnh by trc . Chng hn, ct ProductID l mt kiu int trong SQL Server, v tra tm kiu int SQL server ny trong Bng 9.4, bn c th nhn thy bn cn s dng phng thc GetInt32() thu c gi tr ct nh mt C# int. Bng 9.5 tng kt nhng tn ct, nhng kiu SQL Server, nhng phng thc Get*(), v nhng kiu tr li C# cn thit truy xut nm ct t Bng Products.
Bng 9.5: nhng ct ca bng, nhng kiu, v nhng phng thc. TN CT KIU CT TRONG SQL Server PHNG THC GET* KIU TR V C# ProductID int GetInt32() int ProductName nvarchar GetString() string UnitPrice money GetDecimal() decimal UnitsInStock smallint GetInt16() short Discontinued bit GetBoolean() bool Chng ta hy gi thit rng bn c mt i tng SqlDataReader t tn productsSqlDataReader v n s c s dng c nm ct t bng Products. Vng lp "while" sau y s dng phng thc Get*(), v nhng kiu C# c tr li c trnh by trong Bng 9.5 thu c nhng gi tr ct t productsSqlDataReader:
while (productsSqlDataReader.Read()) { int productID = productsSqlDataReader.GetInt32(productIDColPos); Console.WriteLine("productID = " + productID);
short unitsInStock = productsSqlDataReader.GetInt16(unitsInStockColPos); Console.WriteLine("unitsInStock = " + unitsInStock);
bool discontinued = productsSqlDataReader.GetBoolean(discontinuedColPos); Console.WriteLine("discontinued = " + discontinued); } Nh bn thy, lm bin ca kiu thch hp c to ra trong vng lp "while" ny, mi bin c dng ct gi kt qu tr v t phng thc Get*(). Chng hn, bin ProductID c dng ct gi gi tr ct ProductID, v do ProductID l kiu int SQL Server, kiu C# thch hp vi bin ProductID l int. ly gi tr ct ProductID nh mt C# int, Bn gi phng thc GetInt32().Tng t, bin productName l mt chui C# v c s dng ct gi gi tr ct ProductName. Ct ny thuc kiu nvarchar trong SQL Server, v ly gi tr ct ProductName , phng thc GetString() c s dng.
Tt nhin, m ny ph thuc vo nhng thng tin ca bn nm bt v kiu ca ct c s d liu. Nu bn khng bit v kiu ca mt ct. bn c th s dng trnh duyt server (Server Explorer) ca Visual Studio .NET. Chng hn,Hnh 9.1 cho thy nhng chi tit ca ct ProductID trong bng Products. Nh bn thy, ProductID l mt int.
Hnh 9.1: truy tm kiu ca mt ct s dng trnh duyt server (Server Explorer) ca Visual Studio .NET.
Trc khi ng mc ny, Ti s ch cho bn cch ly kiu ca .NET. v kiu c s d liu ca mt ct s dng C#. Bn ly kiu ca .NET i din cho mt ct s dng phng thc GetFieldType() ca i tng DataReader ca bn. th d: Console.WriteLine("ProductID .NET type = " + productsSqlDataReader.GetFieldType(productIDColPos));
M ny s hin th nh sau: ProductID .NET type = System.Int32 Nh bn thy, kiu System.Int32 .NET c dng i din cho ct ProductID. Kiu System.Int32. NET tng ng ti kiu int trong C#. Bn c th xem li s tng ng ca kiu ny Trong Bng 9.3, ch ra trc . Bn c th ly kiu c s d liu cho mt ct s dng phng thc GetDataTypeName() ca i tng DataReader ca bn. th d:
Console.WriteLine("ProductID database type = " + productsSqlDataReader.GetDataTypeName(productIDColPos));
Th d ny hin th:
ProductID database type = int Nh bn thy, ct ProductID thuc kiu int trong SQL Server. Danh sch 9.2 s dng nhng v d m c trnh by trong mc ny.
/* StronglyTypedColumnValues.cs illustrates how to read column values as C# types using the Get* methods */
using System; using System.Data; using System.Data.SqlClient;
class StronglyTypedColumnValues { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID"); int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName"); int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice"); int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock"); int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");
// use the GetFieldType() method of the DataReader object // to obtain the .NET type of a column Console.WriteLine("ProductID .NET type = " + productsSqlDataReader.GetFieldType(productIDColPos)); Console.WriteLine("ProductName .NET type = " + productsSqlDataReader.GetFieldType(productNameColPos)); Console.WriteLine("UnitPrice .NET type = " + productsSqlDataReader.GetFieldType(unitPriceColPos)); Console.WriteLine("UnitsInStock .NET type = " + productsSqlDataReader.GetFieldType(unitsInStockColPos)); Console.WriteLine("Discontinued .NET type = " + productsSqlDataReader.GetFieldType(discontinuedColPos));
// use the GetDataTypeName() method of the DataReader object // to obtain the database type of a column Console.WriteLine("ProductID database type = " + productsSqlDataReader.GetDataTypeName(productIDColPos)); Console.WriteLine("ProductName database type = " + productsSqlDataReader.GetDataTypeName(productNameColPos)); Console.WriteLine("UnitPrice database type = " + productsSqlDataReader.GetDataTypeName(unitPriceColPos)); Console.WriteLine("UnitsInStock database type = " + productsSqlDataReader.GetDataTypeName(unitsInStockColPos)); Console.WriteLine("Discontinued database type = " + productsSqlDataReader.GetDataTypeName(discontinuedColPos));
// read the column values using Get* methods that // return specific C# types while (productsSqlDataReader.Read()) { int productID = productsSqlDataReader.GetInt32(productIDColPos); Console.WriteLine("productID = " + productID);
productsSqlDataReader.Close(); mySqlConnection.Close(); } } u ra ca chng trnh ny nh sau: ProductID .NET type = System.Int32 ProductName .NET type = System.String UnitPrice .NET type = System.Decimal UnitsInStock .NET type = System.Int16 Discontinued .NET type = System.Boolean ProductID database type = int ProductName database type = nvarchar UnitPrice database type = money UnitsInStock database type = smallint Discontinued database type = bit productID = 1 productName = Chai unitPrice = 18 unitsInStock = 39 discontinued = False productID = 2 productName = Chang unitPrice = 19 unitsInStock = 17 discontinued = False productID = 3 productName = Aniseed Syrup unitPrice = 10 unitsInStock = 13 discontinued = False productID = 4 productName = Chef Anton's Cajun Seasoning unitPrice = 22 unitsInStock = 53 discontinued = False productID = 5 productName = Chef Anton's Gumbo Mix unitPrice = 21.35 unitsInStock = 0 discontinued = True
S DNG NHNG PHNG THC GetSql*() C NHNG GI TR CT:
b xung thm v s s dng nhng phng thc Get* c nhng gi tr ct nh nhng kiu C# tiu chun, nu bn ang s dng SQL Server, bn c th cng s dng nhng phng thc GetSql *. Nhng phng thc GetSql* tr li nhng gi tr nh nhng kiu Sql* , n tng ng vi nhng kiu thc t c s dng bi SQL Server trong c s d liu.
Ghi ch Bn c th thy tt c nhng phng thc GetSql * trongBng 9.2, ch ra trc . Nhng phng thc GetSql* v nhng kiu Sql* c nh ngha trong khng gian tn System.Data. SqlTypes, v chng dnh ring cho SQL Server. Ngoi ra, Nhng phng thc GetSql* cng c trng i vi lp SqlDataReader. Vic s dng nhng phng thc GetSql* v nhng kiu Sql* gip ngn nga nhng li do s chuyn i kiu gy ra bi s mt chnh xc trong nhng gi tr s. Nhng phng thc GetSql* lun nhanh hn so vi nhng phng thc Get*() tng ng ca chng. Bi v nhng phng thc GetSql* khng cn chuyn i gia nhng kiu SQL Server v nhng kiu C# tiu chun, cn nhng phng thc Get*() li phi thc hin .
Mo nh : Nu bn ang s dng SQL Server, nn lun s dng nhng phng thc GetSql* v nhng kiu Sql* hn l nhng phng thc Get*() v nhng kiu C# tiu chun . Ti trnh by vi bn nhng phng thc Get*() trc ch v chng lm vic vi nhng c s d liu khng thuc SQL Server. Bng 9.6 cho thy nhng kiu Sql* v nhng gi tr c th c ct gi trong nhng kiu ny. Bng 9.6: Sql* TYPES Sql* TYPE VALUES SqlBinary Mt chui di bin ca d liu nh phn. SqlBoolean Mt s nguyn vi mt gi tr 1 hoc 0 . SqlByte Mt Gi tr s nguyn khng du 8-bit gia 0 v 2 8 (255). SqlDateTime Mt gi tr ngy thng v thi gian gia 12:00:00 AM thng ging 1, 1753 v 11:59:59 PM thng chp 31, 9999. chnh xc ti mi 3.33 mili-giy . SqlDecimal mt gi tr s chnh xc v quy m c nh gia -10 38 + 1 v 10 38 - 1. SqlDouble Mt s du chm ng 64-bit gia -1.79769313486232E308 and 1.79769313486232E308 vi 15 ch s c ngha ca chnh xc. SqlGuid Mt gi tr s nguyn mu (16 byte) v duy nht ngang qua tt c cc my tnh v nhng mng. SqlInt16 Mt s nguyn c du 16-bit gia -2 15 (-32,768) v 2 15 (32,767). SqlInt32 Mt s nguyn c du 32-bit gia -2 31 (-2,147,483,648) v 2 31 (2,147,483,647). SqlInt64 Mt s nguyn c du 64-bit gia -2 63 (-9,223,372,036,854,775,808) v 2 63
(9,223,372,036,854,775,807). SqlMoney Mt gi tr tin t gia -922,337,203,685,477.5808 v 922,337,203,685,477.5807. chnh xc ti vi 1/10,000 th ca mt n v tin t. SqlSingle Mt s du chm ng 32-bit gia -3.402823E38 and 3.402823E38 vi by ch s c ngha ca chnh xc. SqlString Mt chui di bin ca nhng k t. Bng 9.7 cho thy nhng kiu SQL Server, Nhng kiu Sql tng ng* , v nhng phng thc GetSql* c dng c mt ct nh Kiu Sql*. KIU SQL SERVER KIU Sql* PHNG THC GetSql* bigint SqlInt64 GetSqlInt64() int SqlInt32 GetSqlInt32() smallint SqlInt16 GetSqlInt16() tinyint SqlByte GetSqlByte() bit SqlBoolean GetSqlBoolean() decimal SqlDecimal GetSqlDecimal() numeric SqlDecimal GetSqlDecimal() money SqlMoney GetSqlMoney() smallmoney SqlMoney GetSqlMoney() KIU SQL SERVER KIU Sql* PHNG THC GetSql* float SqlDouble GetSqlDouble() real SqlSingle GetSqlSingle() datetime SqlDateTime GetSqlDateTime() smalldatetime SqlDateTime GetSqlDateTime() char SqlString GetSqlString() varchar SqlString GetSqlString() text SqlString GetSqlString() nchar SqlString GetSqlString() nvarchar SqlString GetSqlString() ntext SqlString GetSqlString() binary SqlBinary GetSqlBinary() varbinary SqlBinary GetSqlBinary() image SqlBinary GetSqlBinary() sql_varient object GetSqlValue() timestamp SqlBinary GetSqlBinary() uniqueidentifier SqlGuid GetSqlGuid()
Tip theo bn s thy cch s dng mt s phng thc trnh by trong Bng 9.7.
MT TH` D S DNG NHNG PHNG THC GetSql*():
Chng ta hy xem xt mt v d m c nhng ct ProductID, ProductName, UnitPrice, UnitsInStock, V Discontinued t bng Products s dng nhng phng thc GetSql*.
hnh dung ra phng thc GetSql*() no c s dng truy xut mt kiu ct c th, bn s dng Bng 9.7, c ch ra trc . Chng hn, ct ProductID l mt kiu int SQL Server, V bn tra kiu ny trong Bng 9.7, bn c th nhn thy bn phi s dng phng thc GetSqlInt32() thu c gi tr ct nh mt C# SqlInt32. Bng 9.8 tng kt nhng tn ct, nhng kiu SQL Server, Nhng phng thc GetSql* , v nhng kiu tr v Sql* cho nhng ct truy xut c t Bng Products.
Bng 9.8: nhng ct ca bng Products, nhng kiu, v nhng phng thc GetSql* COLUMN NAME/ SQL SERVER COLUMN TYPE/ GETSql* METHOD/ Sql* Return Type ProductID int GetInt32() SqlInt32 ProductName nvarchar GetSqlString() SqlString UnitPrice money GetSqlMoney() SqlMoney UnitsInStock smallint GetSqlInt16() SqlInt16 Discontinued bit GetSqlBoolean() SqlBoolean
Chng ta hy gi thit rng bn c mt i tng SqlDataReader c tn productsSqlDataReader v n c th c dng c nhng ct t bng nhng sn phm. Vng lp "while" sau y s dng nhng phng thc GetSql* v nhng kiu Sql* tr v c trnh by trc Trong Bng 9.8 thu c nhng gi tr ct t productsSqlDataReader:
/* StronglyTypedColumnValuesSql.cs illustrates how to read column values as Sql* types using the GetSql* methods */
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes;
class StronglyTypedColumnValuesSql { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID"); int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName"); int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice"); int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock"); int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");
// read the column values using GetSql* methods that // return specific Sql* types while (productsSqlDataReader.Read()) { SqlInt32 productID = productsSqlDataReader.GetSqlInt32(productIDColPos); Console.WriteLine("productID = " + productID);
Nh bn hc Trong Chng 2, mt ct nh ngha l null c th lu tr mt gi tr null( ct trng cha gn gi tr). Mt gi tr null cho bit gi tr ct cha c bit. Mt kiu C# tiu chun khng th ct gi Mt gi tr null, nhng mt kiu Sql* c th.
Chng ta hy xem xt mt v d v vic c mt gi tr null t c s d liu. cho l bn thc hin mt pht biu SELECT truy xut ct UnitPrice cho mt hng t bng nhng sn phm, v ct UnitPrice ny cha mt gi tr null. Nu bn th ct gi gi tr null ny trong mt kiu C# tiu chun (nh mt s thp phn) vi m sau y:
v bn s c ngoi l sau y: System.Data.SqlTypes.SqlNullValueException Bn s cng c ngoi l ny nu Bn th ct gi gi tr null trong mt i tng, nh trong v d sau y: object unitPriceObj = productsSqlDataReader["UnitPrice"]; Bn c th kim tra mt ct c cha mt gi tr null hay khng s dng phng thc IsDBNull() ca mt i tng DataReader. Phng php ny tr v mt i s Boole gi tr true hay false cho bit liu c phi gi tr ct l null. Bn c th s dng kt qu i s Boole ny quyt nh nn lm g. Chng hn:
if (productsSqlDataReader.IsDBNull(unitPriceColPos)) { Console.WriteLine("UnitPrice column contains a null value"); } else { unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos); }
V productsSqlDataReader.IsDBNull(unitPriceColPos) tr v true, v d ny hin th kt qu sau:
UnitPrice column contains a null value
Nh c cp, Mt kiu Sql* c th ct gi mt gi tr null. Mt gi tr null c ct gi nh mt gi tri ' null '. Chng hn: SqlMoney unitPrice = productsSqlDataReader.GetSqlMoney(unitPriceColPos); Console.WriteLine("unitPrice = " + unitPrice); Nhng kt qu ca v d ny:
unitPrice = Null Mi kiu trong nhng kiu Sql* cng u c mt thuc tnh Boolean c tn IsNull l true khi i tng Sql * cha mt gi tr null. Chng hn:
Console.WriteLine("unitPrice.IsNull = " + unitPrice.IsNull); Nhng kt qu ca v d ny: unitPrice.IsNull = True true c trnh by bi v unitPrice cha mt gi tr null.
THC THI NHIU PHT BIU SQL:
in hnh, chng trnh C# v c s d liu ca bn s chy trn nhng my tnh khc nhau v truyn thng qua mt mng. Mi ln bn thc hin mt lnh trong chng trnh ca bn, n phi hnh trnh qua mng ti c s d liu v c thc hin bi c s d liu, v bt k kt qu no phi c gi tr li ngang qua mng n chng trnh ca bn. l s qu ti giao thng mng! Mt cch tim tng gim bt giao thng mng l thc hin nhiu cu lnh SQL ti cng mt thi im.
Trong mc ny, bn s thy cch thc thi nhiu pht biu SELECT v truy xut kt qu, v bn s thy cch thc hin nhiu pht biu SELECT, INSERT, UPDATE , v DELETE nh th no, v s t xen k cc lnh ra sao.
THC THI NHIU PHT BIU SELECT:
Chng ta hy xem xt cch thc hin nhiu pht biu SELECT v truy xut nhng kt qu nh th no . M sau y u tin to ra mt i tng SqlCommand c tn mySqlCommand v gn thuc tnh CommandText ti ba pht biu SELECT khc nhau : SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName " + "FROM Products " + "ORDER BY ProductID;" + "SELECT TOP 3 CustomerID, CompanyName " + "FROM Customers " + "ORDER BY CustomerID;" + "SELECT TOP 6 OrderID, CustomerID " + "FROM Orders " + "ORDER BY OrderID;";
Ch tt c nhng pht biu SELECT c tch ra bi nhng du chm phy. _________________________________________________________________________________________ S DNG TABLE Joins Cn thn ch truy xut nhng hng v nhng ct bn tht s cn. ng thi, chc chn rng bn s dng nhng pht biu SELECT m truy xut nhng hng t nhiu bng. Chng hn, nu bn mun xem tt c nhng n t (orders) c t bi khch hng c CustomerID l ALFKI, ng thc hin hai pht biu SELECT ring bit truy nhp nhng nhng bng khch hng v n t . Thay vo , s dng mt table join, nh c trnh by trong pht biu SELECT sau y: SELECT Customers.CustomerID, CompanyName, OrderID FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID AND Customers.CustomerID = 'ALFKI'; _______________________________________________________________________________________ chy nhng cu lnh SQL u, bn gi phng thc ExecuteReader() , n tr v mt i tng SqlDataReader: SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
Lnh s tr li ba tp hp kt qu, mt cho mi pht biu SELECT. c tp hp kt qu u tin , bn gi phng thc Read() ca mySqlDataReader. Phng thc Read() tr v false khi khng cn hng cho s c. Khi bn ch cui ca mt tp hp kt qu, bn gi phng thc NextResult() ca mySqlDataReader trc khi c tp hp kt qu k tip. Phng thc NextResult s chuyn mySqlDataReader v tp hp kt qu k tip v tr v false khi khng cn tp hp kt qu no.
M sau y minh ha s s dng phng thc Read() V NextResult() c ba tp hp kt qu t nhng pht biu SELECT. do { while (mySqlDataReader.Read()) { Console.WriteLine("mySqlDataReader[0] = " + mySqlDataReader[0]); Console.WriteLine("mySqlDataReader[1] = " + mySqlDataReader[1]); } } while (mySqlDataReader.NextResult());
Ch s s dng ca vng lp ngoi "do ...while loop", th gi tr tr v t mySqlDataReader.NextResult() ti im kt thc. V vng lp "do ...while loop" kim tra iu kin cui vng, iu c ngha l nhng pht biu trong vng lp "do ...while loop" c thc hin t nht mt ln. Bn mun t lnh gi NextResult() cui v trc tin n th tr mySqlDataReader ti tp hp kt qu k tip v sau tr li kt qu i s Boole xem liu c phi cn c mt tp kt qu khc di chuyn Ti. Nu bn t lnh gi NextResult() Trong mt vng lp "while loop" bnh thng, th mySqlDataReader s b qua qua tp hp kt qu u tin, v bn khng mun lm iu !
Danh sch 9.4 minh ha cch thc hin nhiu pht biu SELECT v c nhng kt qu.
/* ExecuteMultipleSelects.cs illustrates how to execute multiple SELECT statements using a SqlCommand object and read the results using a SqlDataReader object */
using System; using System.Data; using System.Data.SqlClient;
class ExecuteSelect { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// read the result sets from the SqlDataReader object using // the Read() and NextResult() methods do { while (mySqlDataReader.Read()) { Console.WriteLine("mySqlDataReader[0] = " + mySqlDataReader[0]); Console.WriteLine("mySqlDataReader[1] = " + mySqlDataReader[1]); } Console.WriteLine(""); // visually split the results } while (mySqlDataReader.NextResult());
mySqlDataReader.Close(); mySqlConnection.Close(); } } u ra ca chng trnh ny nh sau: mySqlDataReader[0] = 1 mySqlDataReader[1] = Chai mySqlDataReader[0] = 2 mySqlDataReader[1] = Chang mySqlDataReader[0] = 3 mySqlDataReader[1] = Aniseed Syrup mySqlDataReader[0] = 4 mySqlDataReader[1] = Chef Anton's Cajun Seasoning mySqlDataReader[0] = 5 mySqlDataReader[1] = Chef Anton's Gumbo Mix
mySqlDataReader[0] = ALFKI mySqlDataReader[1] = Alfreds Futterkiste mySqlDataReader[0] = ANATR mySqlDataReader[1] = Ana Trujillo3 Emparedados y helados mySqlDataReader[0] = ANTON mySqlDataReader[1] = Antonio Moreno Taquera
THC THI NHIU PHT BIU SELECT, INSERT, UPDATE, V DELETE:
Bn c th t xen nhiu pht biu SELECT, INSERT, UPDATE, v DELETE. iu ny c th gim thiu giao thng mng bi v bn gi nhiu cu lnh SQL ti c s d liu vo mt chuyn i. M sau y u tin to ra mt i tng SqlCommand c tn mySqlCommand v gn thuc tnh CommandText l tp hp nhiu cu lnh SQL c t xen:
Pht biu INSERT thm mt hng mi vo bng khch hng. Pht biu SELECT u tin truy xut hng mi. Pht biu UPDATE sa i ct CompanyName ca hng. Pht biu SELECT th hai truy xut hng ln na. Pht biu DELETE loi b hng.
Bn c th s dng vng lp "do ...while loop" tng t nh trnh by trong mc trc y truy xut hai tp hp kt qu c tr v bi nhng s pht biu SELECT. Vng lp tng t ny cng lm vic mc d th d thc thi nhng pht biu khng phi l SELECT . n lm vic v ch nhng pht biu SELECT tr li nhng tp hp kt qu, v phng thc NextResult() tr v true ch vi nhng s pht biu SELECT; n tr v false vi nhng cu lnh SQL khc. Bi vy, NextResult() Tr v false cho pht biu INSERT v chuyn n tp hp kt qu cho pht biu SELECT u tin, vn vn.
Danh sch 9.5 minh ha cch thc hin nhiu cu lnh SQL nh th no.
/* ExecuteMultipleSQL.cs illustrates how to execute multiple SQL statements using a SqlCommand object */ using System; using System.Data; using System.Data.SqlClient;
class ExecuteMultipleSQL { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// read the result sets from the SqlDataReader object using // the Read() and NextResult() methods do { while (mySqlDataReader.Read()) { Console.WriteLine("mySqlDataReader[0] = " + mySqlDataReader[0]); Console.WriteLine("mySqlDataReader[1] = " + mySqlDataReader[1]); } Console.WriteLine(""); // visually split the results } while (mySqlDataReader.NextResult());
mySqlDataReader.Close(); mySqlConnection.Close(); } } u ra t chng trnh ny nh sau:
mySqlDataReader[0] = J5COM mySqlDataReader[1] = Jason 5 Company
mySqlDataReader[0] = J5COM mySqlDataReader[1] = Another Jason Company
S DNG MT I TNG DATAREADER TRONG VISUAL STUDIO .NET:
Bn khng th to ra mt i tng DataReader trc quan trong Visual Studio .NET (VS .NET); bn ch c th to ra chng s dng nhng lnh chng trnh. Trong mc ny, bn s thy cch to ra mt i tng SqlDataReader v s dng n truy xut tp hp kt qu t mt i tng SqlCommand nh th no, v bn thy cch to ra s dng VS .NET trong chng trc y. i tng SqlCommand cha mt pht biu SELECT truy xut nhng ct CustomerID, CompanyName, V ContactName t bng khch hng. Bn s hiu cch thc hin pht biu SELECT , c tp hp kt qu s dng i tng SqlDataReader, v hin th tp hp kt qu trong mt iu khin ListView nh th no. Mt iu khin ListView cho php bn xem thng tin c t trong mt li.
Ghi ch Bn c th sa i d n MyDataReader Bn to ra Trong chng trc y, hay nu bn khng mun i theo nhng ch dn trong mc ny, bn c th n gin m d n hon chnh VS .NET cha trong th mc DataReader. m d n c b sung, la chn File Open Project, duyt ti VS .NET Project \ th mc DataReader, v m File WindowsApplication4.csproj .
Nu bn ang sa i ng dng Windows hin c ca bn, ko mt iu khin ListView vo Form ca bn. Hnh 9.2 cho thy mt Form vi mt iu khin ListView. Chc chn rng thuc tnh "Name" ca ListView ca bn c gn tn l listView1 (y l Tn mc nh, v vy bn khng nn thay i n).
Hnh 9.2: thm mt iu khin ListView vo Form
Cnh bo : nu bn m d n c b sung, bn khng cn phi thm mt ListView controI; n n c trn form b xung. Bn s cn thay i thuc tnh ConnectionString ca i tng sqlConnection1, nh th n s kt ni ti c s d liu Northwind SQL Server ca bn. Mt khi bn thit t ConnectionString ca bn, Bn c th chy form bng cch chn Debug Start Without Debugging.
Tip theo, nhn p mt vng trn form ca bn bn ngoi iu khin ListView. thao tc ny lm VS .NET hin th ca s bin tp m , v bn s nhn thy con tr nh v trong phng thc Form1_Load() ; phng thc ny c gi khi form ca bn c ti giai an thot tin . in hnh, y l phng thc m t bn mun thc hin nhng thao tc vi c s d liu ca bn. thit t phng thc Form1_Load() ca bn vi m sau y:
Ch bn thm mt mc vo iu khin ListView s dng phng thc Add(), c truy nhp s dng thuc tnh Items. phng thc Add() ch i mt tham s chui, v do bn gi phng thc ToString() chuyn i i tng c tr li bi SqlDataReader thnh mt chui. bn cng cn ch bao gm khng gian tn khi tham chiu n lp SqlDataReader . bn s dng System.Data.SqlClient .SqlDataReader khi to ra i tng SqlDataReader.
M trc y m kt ni c s d liu, to ra mt i tng SqlDataReader, v s dng n c nhng hng t tp hp kt qu c tr li bi i tng SqlCommand. Mi ct ca tp hp kt qu ri c thm vo iu khin ListView s dng phng thc Add().
Hnh 9.3 cho thy m ca phng thc Form1_Load() .
Trc khi bn chy form, bn s cn thm mt chui con cha mt khu cho s kt ni c s d liu ti thuc tnh ConnectString ca i tng SqlConnection ca bn. Cho s ci t SQL Server trong my ca ti , mt khu truy nhp c s d liu Northwind l sa, V thuc tnh ConnectionString ca ti c t l :
data source=localhost;initial catalog=Northwind;persist security info=False;user id=sa;pwd=sa;workstation id=JMPRICE-DT1;packet size=4096
Ch chui con pwd= sa trong chui ny t mt khu.
Cui cng, chy form ca bn bng cch nhn Ctl+ F5 trn bn phm, hay chn Debug Start Without Debugging. Hnh 9.4 trnh by s vn hnh form.
Lu d n MyDataReader ca bn _ chn File Save All. Bn s s dng d n ny trong nhng chng sau . Nu bn mun s dng d n han chnh DataReader hn l sa i d n hin hu ca bn, ng lo lng: bn s c kh nng s dng d n han chnh DataReader cng trong nhng chng sau
TM LC:
Trong chng ny, bn hc cch s dng mt i tng DataReader c nhng kt qu tr li t c s d liu. Nhng i tng DataReader l b phn ca nhng trnh cung cp c qun l, v c ba lp DataReader: SqlDataReader, OleDbDataReader, v OdbcDataReader. Bn s dng mt i tng ca lp SqlDataReader c nhng hng truy xut t mt c s d liu SQL Server; mt i tng ca lp OleDbDataReader c nhng hng t bt k c s d liu no m h tr OLE DB, nh Oracle hay Access; v mt i tng ca lp OdbcDataReader c nhng hng t bt k c s d liu no m h tr ODBC. Nhng i tng DataReader c th c dng c ch nhng hng trong mt hng xui, v bn khng th s dng chng sa i c s d liu, nhng chng cung cp s truy xut rt nhanh nhng hng. Nhng i tng DataReader ng vai tr mt gii php i vi mt i tng Dataset. Nhng i tng Dataset cho php bn lu tr mt bn sao ca nhng hng t c s d liu, v bn c th lm vic vi bn sao ny trong khi ngt kt ni vi c s d liu.
CHNG 10: S DNG NHNNG I TNG DATASET LU TR D LIU:
Tng quan:
Trong chng ny, bn s hc nhng chi tit v vic s dng Dataset lu tr nhng kt qu tr v t c s d liu. Nhng i tng Dataset cho php bn lu tr mt bn sao ca thng tin t c s d liu, v bn c th lm vic vi bn sao ny trong khi ngt ra khi c s d liu. Khng ging nhng i tng b cung cp c qun l Nh SqlDataReader, Mt Dataset l chung v bi vy n lm vic vi bt k c s d liu no. Mt i tng Dataset cng cho php bn sa i nhng hng v c nhng hng trong bt k trt t no, khng ging Mt SqlDataReader, ch cho php bn c nhng hng theo mt hng xui tun t. y khng phi ni l nhng i tng SqlDataReader l km: nh bn hc trong Chng 9, chng cung cp s truy nhp rt nhanh n d liu.
Bn s cng hc nhng chi tit ca vic s dng mt i tng DataAdapter c nhng hng t c s d liu vo trong mt Dataset. DataAdapter l mt b phn ca nhng lp cung cp c qun l, v c ba lp DataAdapter: SqlDataAdapter, OleDbDataAdapter, V OdbcDataAdapter. Bn s dng mt DataAdapter sao chp nhng hng t c s d liu n Dataset ca bn v cng y bt k thay i no Bn thc hin ti nhng hng trong Dataset ca bn ti c s d liu. Bn s xem cch thc hin nhng thay i n nhng hng trong mt Dataset v y nhng thay i ti c s d liu trong Chng 11, "s dng nhng i tng Dataset Sa i D liu." Trong chng ny, bn s tp trung vo vic sao chp nhng hng t c s d liu v lu tr chng trong mt Dataset.
Nhng mc chnh trong chng ny: Lp SqlDataAdapter To ra mt i tng SqlDataAdapter Lp Dataset To ra mt i tng Dataset C tr mt i tng Dataset S dng phng thc Merge()_ (Ha trn) Vit v c XML s dng mt i tng Dataset V bn nhng bng v nhng ct To v s dng nhng lp Dataset nh kiu mnh . To ra mt i tng DataAdapter v i tng Dataset s dng Visual Studio .NET
LP SQLDATAADAPTER:
Bn s dng mt i tng ca lp SqlDataAdapter ng b ha d liu c ct gi trong mt i tng Dataset vi mt c s d liu SQL Server. Bn s dng mt i tng ca lp OleDbDataAdapter ng b ha d liu vi mt c s d liu h tr OLE DB, Nh Oracle hay Access. Bn s dng mt i tng ca lp OdbcDataAdapter ng b ha d liu vi mt c s d liu h tr ODBC. Ghi ch D lp SqlDataAdapter c ch nh ring cho SQL Server, nhiu thuc tnh v phng thc trong lp ny cng tng t nh trong lp OleDbDataAdapter v OdbcDataAdapter.
Bng 10.1 trnh by mt s thuc tnh ca SqlDataAdapter. Thuc tnh Ki M t AcceptChangesDuringFill bool ly hay t mt gi tr bool ch nh liu phng thc AcceptChanges() c c gi sau khi mt i tng DataRow c thm, iu chnh, hay loi b trong mt i tng DataTable. gi tr mc nh l true ContinueUpdateOnError bool ly hay t mt gi tr bool ch nh liu c phi tip tc cp nht c s d liu khi mt li xut hin. khi t l true, khng c ngoi l no c xut ra khi mt li xut hin trong thi gian cp nht mt hng. s cp nht ca hng c b qua v thng tin li c t trong thuc tnh RowError ca DataRow m gy ra li. DataAdapter tip tc cp nht nhng hng k tip. khi t l false, mt ngoi l c nm khi mt li xut hin. gi tr mc nh l false. DeleteCommand SqlCommand ly hay gn mt lnh cha mt pht biu SQL DELETE hoc mt lnh gi th tc lu tr loi b nhng hng t c s d liu. InsertCommand SqlCommand ly hay gn mt lnh cha mt pht biu SQL INSERT hoc mt lnh gi th tc lu tr thm nhng hng vo c s d liu. MissingMappingAction MissingMappingAction ly hay gn hnh ng thc thi khi bng hay ct u vo khng c mt bng hay ct thch ng trong tp hp TableMappings. Nhng gi tr cho hnh ng ny n t lp lit k System.Data.MissingMappingAction vi nhng li Thuc tnh Ki M t thnh vin, Error, Ignore v Passthrough: . Li c ngha l mt SystemException c tung ra. . Ignore c nghi bng hay ct c l i v khng c. . Passthrough c ngha bng hay ct c thm vo Dataset vi tn nguyn bn ca n. Gi tr mc nh l Passthrough. MissingSchemaAction MissingSchemaAction ly hay t hnh ng thc thi khi ct u vo khng c mt ct thch ng trong tp hp ct ca i tng DataTable. Nhng gi tr cho hot ng ny n t lp lit k System.Data.MissingSchemaAction vi nhng thnh vin : Add, AddWithKey, Error, and Ignore: . Add c nghi ct c thm vo DataTable. . AddWithKey c nghi thng tin ct v kha chnh c thm vo DataTable. . Error c ngha mt SystemException c nm. . Ignore c ngha ct c l i v khng c. Mc nh l Add. SelectCommand SqlCommand ly hay t mt lnh cha mt pht biu SQL SELECT hay lnh gi th tc lu tr truy xut nhng hng t c s d liu. TableMappings DataTableMappingCollection Ly mt tp hp gin bng (DataTableMappingCollection) cha nh x gia mt bng c s d liu v mt i tng DataTable trong Dataset. UpdateCommand SqlCommand ly hay t mt lnh cha nhng mt pht biu SQL UPDATE hoc lnh gi th tc sa i nhng hng trong c s d liu. Bng 10.2 trnh by mt s phng thc SqlDataAdapter. Phng thc Kiu tr v M t Fill() int Qu ti . ng b ha nhng hng trong i tng Dataset ph hp vi nhng hng trong c s d liu. gi tr int c tr v bi phng thc ny l s lng hng c ng b ha trong Dataset vi c s d liu. FillSchema() DataTable DataTable[] Qu ti . Thm mt DataTable vo mt i tng Dataset v nh hnh m hnh ph hp vi c s d liu. GetFillParameters() IDataParameter[] tr li mt mng ca bt k tham s no t cho pht biu SQL SELECT. Update() int Qu ti. gi nhng pht biu SQL tng ng INSERT, UPDATE, hay DELETE hay lnh gi th tc lu tr (lu tr trong thuc tnh tng ng InsertCommand, UpdateCommand, v DeleteCommand) cho mi hng c thm, c sa i, hay c loi b t mt i tng Phng thc Kiu tr v M t DataTable. gi tr int c tr li bi phng thc ny l s lng hng c cp nht.
Bng 10.3 trnh by mt s s kin SqlDataAdapter. S kin Event EVENT HANDLER i tng s l s kin M t
FillError FillErrorEventHandler pht ra khi mt li xut hin trong thi gian in d liu ca mt thao tc. RowUpdating RowUpdatingEventHandler pht ra trc khi mt hng c thm vo, iu chnh, hay xa trong c s d liu. RowUpdated RowUpdatedEventHandler Pht ra sau khi thm, iu chnh, hay xa mt hng trong c s d liu.
Bn s hc cch s dng mt s thuc tnh v nhng phng thc ny lu tr d liu trong nhng i tng Dataset trong chng ny. Bn s thy cch s dng nhng thuc tnh , nhng phng thc v nhng s kin khc nh th no trong Chng 11, trong bn s hc sa i d liu trong i tng Dataset nh th no , v sau gn nhng s sa i ti c s d liu.
TO MT I TNG SQLDATAPDAPTER:
Bn to mt i tng SqlDataAdapter s dng mt trong s nhng b khi to SqlDataAdapter sau y : 1, SqlDataAdapter() 2, SqlDataAdapter(SqlCommand mySqlCommand) 3, SqlDataAdapter(string selectCommandString, SqlConnection mySqlConnection) 4, SqlDataAdapter(string selectCommandString, string connectionString)
Vi _ mySqlCommand i din i tng SqlCommand ca cc bn. _ selectCommandString ch nh pht biu SELECT hay lnh gi th tc lu tr ca bn . _ mySqlConnection i din i tng kt ni (SqlConnection) ca bn. _ connectionString ch nh chui kt ni ca bn kt ni c s d liu. V d sau y s dng b khi to SqlDataAdapter() to ra mt i tng SqlDataAdapter. SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); Trc khi s dng mySqlDataAdapter lu tr mt Dataset bn phi gn thuc tnh SelectCommand ca n vi mt SqlCommand cha mt pht biu SELECT hay lnh gi th tc lu tr. V d sau y to ra mt i tng SqlCommand vi thuc tnh CommandText ca n c gn ti mt pht biu SELECT m s truy xut nm hng u t bng sn phm, v thuc tnh CommandText ca mySqlDataAdapter c gn n i tng SqlCommand va ni trn: SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; mySqlDataAdapter.SelectCommand = mySqlCommand;
V d k tip s dng b khi to SqlDataAdapter(SqlCommand MySqlCommand) : SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);
V d k tip s dng b khi to SqlDataAdapter(string SelectCommandString, SqlConnection mySqlConnection) :
SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); string selectCommandString = "SELECT TOP 10 ProductID, ProductName, UnitPrice " + "FROM Products " + ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(selectCommandString, mySqlConnection); V d cui cng s dng b khi to SqlDataAdapter(string SelectCommandString, chui connectionString) : string selectCommandString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; string connectionString = "SELECT TOP 10 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(selectCommandString, connectionString);
Cnh bo b khi dng ny gy ra i tng SqlDataAdapter to ra mt i tng SqlConnection ring bit khc. y in hnh l iu khng ai mong mun t mt tnh hung thc thi v vic m mt kt ni n c s d liu s dng mt i tng SqlConnection nm gi mt thi gian tng i di. do bn cn phi trnh s dng b khi dng SqlDataAdapter(string selectCommandString, String connectionString). Thay vo , bn phi s dng mt i tng SqlConnection hin hu vi i tng SqlDataAdapter ca cc bn.
Mt i tng DataAdapter khng ct gi nhng hng: n n thun hnh ng nh mt ng dn gia c s d liu v mt i tng ca lp Dataset. Trong mc k tip, bn s hc v lp Dataset.
LP DATASET:
Bn s dng mt i tng ca lp Dataset i din cho mt bn sao cc b ca thng tin c ct gi trong c s d liu. Bn c th thc hin nhng thay i ti bn sao cc b ny trong Dataset ca bn v sau sau ng b ha nhng s thay i vi c s d liu thng qua mt DataAdapter. Mt Dataset c th i din cho nhng cu trc c s d liu nh nhng bng, nhng hng v nhng ct. Bn c th thm ch thm nhng s rng buc vo nhng bng cc b c ct gi ca bn gim st nhng s rng buc kha chnh v kha ngoi. Hnh 10.1 trnh by Dataset v mi quan h ca n ti vi i tng bn c th lu tr bn trong n. Nh bn c th thy t hnh ny, bn c th lu tr nhiu i tng DataTable trong mt Dataset, vn vn.
Bng 10.4: nhng thuc tnh Dataset
Thuc tnh Kiu M t CaseSensitive bool ly hay gn mt gi tr bool ch nh liu c phi nhng s so snh chui bn trong nhng i tng DataTable th ph thuc kiu ch. DataSetName string ly hay gn tn ca i tng Dataset hin thi. DefaultViewManager DataViewManager ly mt view chnh l ca d liu c lu tr trong i tng Dataset . Bn s dng mt view lc, tm kim, v nh hng Dataset. EnforceConstraints bool ly hay gn mt gi tr bool ch nh liu c phi nhng quy tc rng buc c gn theo, sau khi cp nht thng tin trong i tng Dataset. ExtendedProperties PropertyCollection ly mt tp hp (PropertyCollection) ca thng tin ngi s dng. Bn c th s dng PropertyCollection lu gi nhng chui vi bt k thng tin b sung no bn mun. Bn s s dng phng thc Add() thng qua ExtendedProperties thm mt chui. HasErrors bool ly mt gi tr bool ch nh liu c phi c nhng li trong bt k hng no trong nhng bng ca i tng Dataset. Locale CultureInfo ly hay gn mt i tng CultureInfo cho Dataset. mt i tng CultureInfo cha thng tin v mt mt c bit bao gm tn ca n, h thng ghi v lch. Namespace string ly hay gn namespace cho i tng Dataset. namespace l Thuc tnh Kiu M t mt chui c s dng khi c v vit mt ti liu XML s dng nhng phng thc ReadXml(), WriteXml(), ReadXmlSchema(), v WriteXmlSchema() . namespace c dng gom nhm nhng thuc tnh XML v nhng phn t. Prefix string ly hay gn tin t XML cho namespace Dataset. Tin t c s dng trong mt ti liu XML xc nh nhng phn t l thuc v namespace ca i tng Dataset. Relations DataRelationCollection ly mt tp hp nhng quan h (DataRelationCollection) m cho php s dn hng t mt bng cha n mt bng con. Mt tp hp DataRelationCollection cha nhng i tng DataRelation. Tables DataTableCollection ly mt tp hp ca bng (DataTableCollection) m cha nhng i tng DataTable c lu tr trong Dataset.
Bng 10.5 trnh by mt s phng thc ca Dataset. Phng thc Kiu tr v M t AcceptChanges() void Hiu lc ha tt c nhng s thay i thc hin vi i tng Dataset t khi n c ti hay t ln cui cng phng thc AcceptChanges() c gi. BeginInit() void S dng bi trnh thit k ca Visual Studio .NET khi to mt Dataset c dng trong mt form hay thnh phn. Clear() void loi b tt c cc hng t tt c cc bng trong i tng Datset. Clone() DataSet Sao chp cu trc ca i tng Dataset v tr v bn sao ny. bn sao ny cha tt c nhng m hnh, nhng quan h, nhng s rng buc v d liu. Copy() DataSet Copy cu trc v d liu ca i tng Dataset v tr li bn sao ny. bn sao chp cha ng tt c nhng m hnh, nhng quan h, nhng s rng buc, v d liu. EndInit() void s dng bi trnh thit kVisual Studio .NET kt thc s khi to ca mt Dataset c dng trong mt form hay thnh phn. GetChanges() DataSet Qa ti. ly mt bn sao ca mi thay i thc hin ti i tng Dataset t cui s ti hay t ln cui cng phng thc AcceptChanges() c gi . GetXml() string tr v trnh by XML ca d liu c lu gi trong i tng Dataset. GetXmlSchema() string Tr v bn trnh by XML ca m hnh cho i tng Dataset. HasChanges() bool S qu ti . Tr li mt gi tr bool ch bo liu c phi i tng Dataset c thay i m cha c giao ph(cp nht c s d liu). Merge() void Qu ti. trn Dataset ny vi i tng Dataset c ch nh khc. ReadXml() XmlReadMode Qu ti . ti d liu t mt file XML vo trong i tng Dataset. ReadXmlSchema() void Qu ti. np mt m hnh t mt file XML sp xp vo trong i tng Dataset. RejectChanges() void Hu tt c thay i c thc hin vi i tng Dataset t khi n c to ra hay t ln cui cng phng thc AcceptChanges() c gi . Reset() void t li i tng Dataset ti trng thi nguyn bn ca n. WriteXml() void Qu ti. Vit d liu t i tng Dataset n mt file XML. WriteXmlSchema() void Qu ti . Vit m hnh ca i tng Dataset ti mt file XML.
Bng 10.6 trnh by mt trong s nhng s kin Dataset. MergeFailed MergeFailedEventHandler pht ra khi mt n lc thm mt DataRow vo mt Dataset m gi tr kha chnh ca DataRow ny tn ti trong Dataset.
Trong mc k tip, bn s hc cch to ra mt i tng Dataset nh th no.
TO MT I TNG Dataset:
Bn to ra mt i tng Dataset s dng mt trong nhng b khi to Dataset sau y:
1, DataSet() 2, DataSet(string dataSetNameString)
dataSetNameString l chui gn ti thuc tnh DataSetName ca i tng dataset ca bn. S thit t thuc tnh DataSetName l ty chn.
V d sau y s dng b khi dng Dataset() to mt i tng Dataset.
DataSet myDataSet = new DataSet();
V d k tip s dng b khi to Dataset(string dataSetNameString) to mt i tng dataset.
DataSet myDataSet = new DataSet("myDataSet");
LU TR MT I TNG DATASET:
Trong mc ny bn lm s hc cch lu tr mt Dataset nh th no_ s dng phng thc Fill() ca mt i tng DataAdapter. c bit, bn s thy cch lu tr mt Dataset nh th no, s dng:
mt pht biu SELECT. Mt phm vi nhng hng mt th tc ni (stored procedure)
S DNG MT PHT BIU SELECT:
Trc khi bn lu tr mt Dataset u tin bn cn mt Connection, mt Command v Mt DataAdapter:
SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open();
Ch : i tng mySqlCommand cha mt pht biu SELECT truy xut ProductID, ProductName, v nhng ct UnitPrice ca nam hng u tin t bng Products. ______________________________________________________________________________________
Truy xut t nhiu bng ng nhin, bn khng c gii hn mt pht biu SELECT m truy xut t mt bng n. Bn c th s dng mt pht biu SELECT m truy xut t nhiu bng ang s dng mt lin kt, tuy nhin, Bn cn phi in hnh trnh thc hin iu ny v mt DataTable c ngha c dng lu gi nhng hng t mt bng c s d liu n. _________________________________________________________________________________________
Tip theo, lu tr myDataSet vi nhng hng t bng Products, bn gi phng thc Fill() ca mySqlDataAdapter. Chng hn: int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); Gi tr Int c tr li bi phng thc Fill() l s lng hng c ng b ha gia Dataset v c s d liu qua DataAdapter. Trong v d trc, int l s lng hng c sao chp t bng Product n myDataSet v c gn l 5- tc s lng hng c truy xut bi pht biu Select c trnh by trc.
Tham s u tin gn ti phng thc Fill() l Dataset ca bn, v tham s th hai l mt chui cha tn bn mun gn cho DataTable c to ra trong Dataset ca bn.
Ghi ch: Tn bn gn cho DataTable ca bn khng phi trng tn ca bng c s d liu. Bn c th s dng bt k chui no, in hnh bn vn cn phi s dng tn ging nh vy, v n gip bn theo di ci m bng c s d liu s dng lu tr DataTable ny.
Khi bn gi phng thc Fill() ln u, nhng bc sau y c thc hin bi ADO.NET: 1. pht biu SELECT trong SqlCommand ca bn c thc thi. 2. mt i tng DataTable mi c to ra trong Dataset ca bn. 3. DataTable ca bn c lu tr cng vi tp kt qu tr v bi pht biu SELECT. Nu bn kt thc vi c s d liu sau khi gi phng thc Fill() bn cn phi ng i tng kt ni ca bn s dng phng thc Close() . mySqlConnection.Close();
Ghi ch: phng thc Fill() s tht s m v ng Kt ni cho bn nu bn khng m n trc, tuy nhin, tt nht l m v ng kt ni mt cch tng minh bi v cch ny l b thu dn m chng trnh ca bn thc hin. ng thi, nu bn gi phng thc Fill() nhiu ln qua mt on ngn ca m, bn s mun gi kt ni c s d liu m v ch ng n khi bn han tt. Dataset by gi c lu tr vi mt DataTable tn l Products . Bn c th c Products DataTable t myDataSet s dng v d sau y:
Bn c th cng c Products DataTable s dng mt gi tr int :
DataTable myDataTable = myDataSet.Tables[0];
Bn c th trnh by nhng gi tr ct cho mi hng myDataTable s dng vng lp foreach sau y duyt qua nhng i tng DataRow c ct gi trong myDataTable; ch s s dng thuc tnh nhng hng ca i tng myDataTable.
Nhng thuc tnh ca hng tr li mt i tng DataRowCollection cho php bn truy nhp tt c nhng i tng DataRow ct gi trong myDataTable. Bn c th c mi gi tr ct mt DataRow s dng tn ca ct; chng hn, c gi tr ct ProductID bn s dng myDataRow[ " ProductID "]. Bn cng c th s dng s ch v tr ca ct; chng hn, myDataRow[0] tr v gi tr cho ct u tin . y l ct ProductID.
Bn cng c th s dng m sau y duyt qua mi DataTable, DataRow, V DataColumn c ct gi trong myDataSet:
foreach (DataTable myDataTable in myDataSet.Tables) { foreach (DataRow myDataRow in myDataTable.Rows) { foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } } }
Ch bn khng cn bit nhng tn ca nhng i tng DataTable hay DataColumn trnh by chng. S gi phng thcWriteLine() s hin th myDataColumn, n tr v tn ca ct, V myDataRow[myDataColumn], s tr li gi tr ct cho dng hin ti.
Ghi nh :Bn s thy nhng chi tit ca cc lp DataTable, DataRow, v DataColumn trong Chng 11.
Lit k 10.1 trnh by mt chng trnh s dng nhng v d m nu trong mc ny.
/* PopulateDataSetUsingSelect.cs illustrates how to populate a DataSet object using a SELECT statement */
using System; using System.Data; using System.Data.SqlClient;
class PopulateDataSetUsingSelect { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// create a SqlCommand object and set its CommandText property // to a SELECT statement that retrieves the top 5 rows from // the Products table SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID";
// create a SqlDataAdapter object and set its SelectCommand // property to the SqlCommand object SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand;
// create a DataSet object DataSet myDataSet = new DataSet();
// open the database connection mySqlConnection.Open();
// use the Fill() method of the SqlDataAdapter object to // retrieve the rows from the table, storing the rows locally // in a DataTable of the DataSet object Console.WriteLine("Retrieving rows from the Products table"); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); Console.WriteLine("numberOfRows = " + numberOfRows); // close the database connection mySqlConnection.Close();
// get the DataTable object from the DataSet object DataTable myDataTable = myDataSet.Tables["Products"];
// display the column values for each row in the DataTable, // using a DataRow object to access each row in the DataTable foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " + myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]); } } } The output from this program is as follows: Retrieving rows from the Products table numberOfRows = 5 ProductID = 1 ProductName = Chai UnitPrice = 18 ProductID = 2 ProductName = Chang UnitPrice = 19 ProductID = 3 ProductName = Aniseed Syrup UnitPrice = 10 ProductID = 4 ProductName = Chef Anton's Cajun Seasoning UnitPrice = 22 ProductID = 5 ProductName = Chef Anton's Gumbo Mix UnitPrice = 21.35
S DNG MT DI NHNG HNG:
Trong mc ny bn s hc cch lu tr mt Dataset nh th no vi mt phm vi ca nhng hng. By gi, phng thc Fill() b qu ti v mt b phn danh sch ca nhng phng thc Fill() nh sau:
int Fill(DataSet myDataSet) int Fill(DataTable myDataTable) int Fill(DataSet myDataSet, string dataTableName) int Fill(DataSet myDataSet, int startRow, int numOfRows, string dataTableName)
dataTableName: ch nh mt chui cha ng tn ca DataTable in vo. startRow: l mt int ch r v tr ca hng trong tp hp kt qu c (bt u ti 0). NumOfRows: l mt int ch r s lng hng c.
Phm vi ca nhng hng t startRow n startRow+ numOfRows ri c ct gi trong DataTable. Int c tr v bi phng thc Fill() l s lng hng truy xut c t c s d liu.
nh bn c th thy, phng thc Fill() cui cng cho php bn c tr mt Dataset vi mt phm vi nhng hng. V d sau y cho thy cch s dng ca phng thc Fill() ny ct gi mt phm vi ca nhng hng. N truy xut nm hng u tin t bng Products, nhng ct gi ch ba hng trong Products DataTable, Bt u ti v tr 1 (v nhng hng c ghi s bt u ti 0 v tr 1 tng ng ti hng th hai trong tp hp kt qu tr v bi pht biu SELECT) :
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products");
Bin numberOfRows c gn l 3 _ l S lng hng c lu tr vi myDataSet . Mt iu nh l DataAdapter vn truy xut tt c nm hng t bng Products, nhng ch ba hng tht s c dng c tr Dataset: cn hai hng khc b b i.
Lit k 10.2 cho thy mt chng trnh s dng nhng v d m trnh by trong mc ny.
/* PopulateDataSetUsingRange.cs illustrates how to populate a DataSet object with a range of rows from a SELECT statement */
using System; using System.Data; using System.Data.SqlClient;
class PopulateDataSetUsingRange { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); // create a SqlCommand object and set its CommandText property // to a SELECT statement that retrieves the top 5 rows from // the Products table SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open();
// use the Fill() method of the SqlDataAdapter object to // retrieve the rows from the table, storing a range of rows // in a DataTable of the DataSet object Console.WriteLine("Retrieving rows from the Products table"); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products"); Console.WriteLine("numberOfRows = " + numberOfRows);
foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " + myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]); } } } The output from this program is as follows: Retrieving rows from the Products table numberOfRows = 3 ProductID = 2 ProductName = Chang UnitPrice = 19 ProductID = 3 ProductName = Aniseed Syrup UnitPrice = 10 ProductID = 4 ProductName = Chef Anton's Cajun Seasoning UnitPrice = 22
S DNG MT TH TC LU TR:
Bn cng c th c tr mt i tng Dataset s dng mt th tc lu tr tr v mt tp hp kt qu . Chng hn, c s d liu Northwind Ngi phc v SQL cha mt th tc lu tr c gi l CustOrderHist() n tr v nhng sn phm v s lng sn phm c t bi mt khch hng. CustomerID ca khch hng c s dng nh mt tham s cho CustOrderHist().
Danh sch 10.3 trnh by nh ngha ca th tc lu tr CustOrderHist() .
CREATE PROCEDURE CustOrderHist @CustomerID nchar(5) AS SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID = @CustomerID AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName
Ghi ch: Bn khng cn t to ra th tc lu tr CustOrderHist() . N c nh ngha trong c s d liu Northwind.
Vic gi CustOrderHist() v vic lu tr mt Dataset vi tp hp kt qu c tr v l iu d dng. Chng hn, m sau y to ra mt i tng SqlCommand, t i tng CommandText ca vi pht biu thc thi s m gi th tc lu tr CustOrderHist(), v t tham s @CustomerID l ALFKI ( Nhng tham s ni qua trong Chng 8, " Nhng lnh thc thi c s d liu "):
Bn ri s dng m tng t nh trnh by trong mc trc lu tr mt Dataset vi tp hp kt qu c tr v bi CustOrderHist():
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist"); mySqlConnection.Close();
DataTable CustOrderHist cha bn trong myDataSet c lu tr vi tp hp kt qu tr v bi th tc CustOrderHist() .
Danh sch 10.4 trnh by mt chng trnh s dng nhng v d m s dng trong mc ny.
/* PopulateDataSetUsingProcedure.cs illustrates how to populate a DataSet object using a stored procedure */
using System; using System.Data; using System.Data.SqlClient;
class PopulateDataSetUsingProcedure { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// create a SqlCommand object and set its CommandText property // to call the CustOrderHist() stored procedure SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "EXECUTE CustOrderHist @CustomerID"; mySqlCommand.Parameters.Add( "@CustomerID", SqlDbType.NVarChar, 5).Value = "ALFKI";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); Console.WriteLine("Retrieving rows from the CustOrderHist() Procedure"); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist"); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close();
Retrieving rows from the CustOrderHist() Procedure numberOfRows = 11 ProductName = Aniseed Syrup Total = 6 ProductName = Chartreuse verte Total = 21 ProductName = Escargots de Bourgogne Total = 40 ProductName = Flotemysost Total = 20 ProductName = Grandma's Boysenberry Spread Total = 16 ProductName = Lakkalikri Total = 15 ProductName = Original Frankfurter grne Soe Total = 2 ProductName = Raclette Courdavault Total = 15 ProductName = Rssle Sauerkraut Total = 17 ProductName = Spegesild Total = 2 ProductName = Vegie-spread Total = 20
LU TR MT DATASET VI NHIU I TNG TADATABLE:
Bn c th c tr mt Dataset vi nhiu i tng DataTable. Bn c th mun lm iu khi bn cn truy nhp thng tin c ct gi trong nhiu bng trong c s d liu. Bn c th s dng bt k k thut no sau y c tr mt Dataset vi nhiu i tng DataTable : S dng nhiu pht biu SELECT trong cng mt SelectCommand . Thay i thuc tnh CommandText ca SelectCommand trc mi lnh gi phng thc Fill(). S dng nhiu i tng DataAdapter c tr cng mt Dataset .
Chng ta hy xem xt tt c nhng k thut ny.
S DNG NHIU PHT BIU SELECT TRONG CNG MT SelectedCoommand:
Nhng v d sau y t thuc tnh CommandText ca mt SqlCommand vi hai pht biu SELECT ring bit
Ch : mi pht biu SELECT c tch ra bi mt du chm phy (;). Khi nhng pht biu SELECT ny chy, hai tp hp kt qu c tr v: mt cha hai hng t bng Products, tp hp kt qu th hai cha mt hng t bng Customers. Hai tp hp kt qu ny c ct gi trong nhng i tng DataTable ring bit bi m sau y:
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet); mySqlConnection.Close();
Ch : s s dng phng thc Fill(mydataset), khng ch nh tn ca DataTable s c to ra. Thay vo , tn ca hai i tng DataTable (dng ct gi nhng tp kt qu) c t ng gn theo mc nh l Table v Table1. Table ct gi tp hp kt qu t Bng Products, v Table1 ct gi kt qu t nhng Bng Customers.
Tn ca mt i tng DataTable c ct gi trong thuc tnh TableName ca n, v bn c th thay i. Chng hn, m sau y thay i tn ca Table ca Dataset thnh Products v Table1 ca Dataset thnh Customers:
Danh sch 10.5 trnh by mt chng trnh s dng nhng v d m hin s dng trong mc ny.
/* MutlipleDataTables.cs illustrates how to populate a DataSet with multiple DataTable objects using multiple SELECT statements */
using System; using System.Data; using System.Data.SqlClient;
class MultipleDataTables { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// create a SqlCommand object and set its CommandText property // to mutliple SELECT statements SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID;" + "SELECT CustomerID, CompanyName " + "FROM Customers " + "WHERE CustomerID = 'ALFKI';";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close();
// change the TableName property of the DataTable objects myDataSet.Tables["Table"].TableName = "Products"; myDataSet.Tables["Table1"].TableName = "Customers";
foreach (DataTable myDataTable in myDataSet.Tables) { Console.WriteLine("\nReading from the " + myDataTable.TableName + "DataTable"); foreach (DataRow myDataRow in myDataTable.Rows) { foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } } } } } _________________________________________________________________________________________
Reading from the Customers DataTable CustomerID = ALFKI CompanyName = Alfreds Futterkiste
THAY I THUC TNH COMMANDTEXT CA SELECTCOMMAND:
Bn cng c th c tr mt Dataset vi nhiu i tng DataTable bi thay i thuc tnh CommandText ca SelectCommand cho i tng DataAdapter ca bn trc trc mi lnh gi phng thc Fill(). u tin, m sau y c tr mt Dataset vi mt DataTable cha hai hng t bng Products:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); i tng myDataSet by gi cha mt DataTable c tn Products. Tip theo,thuc tnh CommandText cho SelectCommand ca mySqlDataAdapter c thay i ti mt pht biu SELECT truy xut nhng hng t bng Customers, v phng thc Fill() c gi ln na: mySqlDataAdapter.SelectCommand.CommandText = "SELECT CustomerID, CompanyName " + "FROM Customers " + "WHERE CustomerID = 'ALFKI'"; numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close();
i tng MyDataSet by gi cha mt DataTable b sung t tn Customers.
Lit k 10.6 trnh by mt chng trnh s dng nhng v d m dng trong mc ny.
/* MutlipleDataTables2.cs illustrates how to populate a DataSet object with multiple DataTable objects by changing the CommandText property of a DataAdapter object's SelectCommand */
using System; using System.Data; using System.Data.SqlClient;
class MultipleDataTables2 { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); Console.WriteLine("numberOfRows = " + numberOfRows);
Reading from the Customers DataTable CustomerID = ALFKI CompanyName = Alfreds Futterkiste
S DNG NHIU I TNG DATAADAPTER LU TR CNG MT I TNG DATASET.
Bn cng c th c tr cng mt Dataset vi nhiu i tng DataTable s dng nhng i tng DataAdapter khc nhau. Chng hn, gi thit bn c mt Dataset c tn myDataSet c c tr s dng mt SqlDataAdapter c tn mySqlDataAdapter, V myDataSet ny ang cha mt DataTable t tn Products. V d sau y to ra SqlDataAdapter khc v s dng c tr myDataSet vi DataTable khc tn Customers
Lit k 10.7 trnh by mt chng trnh s dng nhng v d m nu trong mc ny
/* utlipleDataTables3.cs illustrates how to populate a DataSet bject with multiple DataTable objects using multiple ataAdapter objects to populate the same DataSet object */
using System; using System.Data; using System.Data.SqlClient; class MultipleDataTables3
Reading from the Customers DataTable CustomerID = ALFKI CompanyName = Alfreds Futterkiste
TRN NHNG I TNG DATAROW, DATASET, V DATATABLE VO TRONG DATASET KHC:
Trong mc ny, bn s hc cch s dng phng thc Merge() trn nhng i tng DataRow, Dataset, v DataTable vo trong Dataset khc nh th no. Bn c th s mun lm iu ny khi Bn c nhiu ngun d liu; v d bn c nhiu d liu t nhiu vn phng khu vc c gi n tr s chnh, v bn cn trn tt c d liu vo trong mt Dataset.
Vi: PreserveChanges: ch r liu c phi nhng s thay i trong Dataset hin thi (Dataset vi phng thc Merge() c gi) s c gi li. MyMissingSchemaAction : ch nh hot ng nm bt khi Dataset hin thi khng c nhng bng hay nhng ct ging nh trong DataRow, Dataset, hay DataTable ang c trn vo trong Dataset ny.
Bn gn myMissingSchemaAction vi mt trong s nhng hng s c nh ngha trong lp lit k System.Data.MissingSchemaAction. Bng 10.7 cho thy nhng hng s nh ngha trong lp lit k MissingSchemaAction. Bng 10.7: Lit k nhng phn t MissingSchemaAction Hng s M t Add Ct hay bng c thm vo Dataset hin thi. Add l mc nh. AddWithKey Thng tin ct v kha chnh c thm vo Dataset hin thi. Error Mt SystemException c tung ra. Ignore Ct hay bng c l i v khng phi c.
Danh sch 10.8 minh ha cch s dng phng thc Merge(). /* Merge.cs illustrates how to use the Merge() method */
using System; using System.Data; using System.Data.SqlClient;
class Merge { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
// populate myDataSet with three rows from the Customers table mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, ContactName, Address " + "FROM Customers " + "WHERE CustomerID IN ('ALFKI', 'ANATR', 'ANTON')"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers");
// populate myDataSet2 with two rows from the Customers table mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, ContactName, Address " + "FROM Customers " + "WHERE CustomerID IN ('AROUT', 'BERGS')"; DataSet myDataSet2 = new DataSet(); mySqlDataAdapter.Fill(myDataSet2, "Customers2");
// populate myDataSet3 with five rows from the Products table mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " + "FROM Products " + "ORDER BY ProductID"; DataSet myDataSet3 = new DataSet(); mySqlDataAdapter.Fill(myDataSet3, "Products");
mySqlConnection.Close();
// merge myDataSet2 into myDataSet myDataSet.Merge(myDataSet2);
// merge myDataSet3 into myDataSet myDataSet.Merge(myDataSet3, true, MissingSchemaAction.Add);
// display the rows in myDataSet foreach (DataTable myDataTable in myDataSet.Tables) { Console.WriteLine("\nReading from the " + myDataTable + "DataTable"); foreach (DataRow myDataRow in myDataTable.Rows) { foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } } } } }
u ra t chng trnh ny nh sau: Reading from the Customers DataTable CustomerID = ALFKI CompanyName = Alfreds Futterkiste ContactName = Maria Anders Address = Obere Str. 57 CustomerID = ANATR CompanyName = Ana Trujillo3 Emparedados y helados ContactName = Ana Trujillo Address = Avda. de la Constitucin 2222 CustomerID = ANTON CompanyName = Antonio Moreno Taquera ContactName = Antonio Moreno Address = Mataderos 2312
Reading from the Customers2 DataTable CustomerID = AROUT CompanyName = Around the Horn ContactName = Thomas Hardy Address = 120 Hanover Sq. CustomerID = BERGS CompanyName = Berglunds snabbkp ContactName = Christina Berglund Address = Berguvsvgen 8
XML l mt nh dng tin li cho s chuyn di thng tin qua li. Bn c th vit ra ni dung ca nhng i tng DataTable c cha trong mt Dataset thnh mt file XML s dng phng thc WriteXml() . file XML c vit bi phng thc ny cha ng nhng tn ct v nhng gi tr ca DataTable .
Bn c th vit ra m hnh ca mt i tng Dataset thnh mt file XML s dng phng thc WriteXmlSchema() . file XML c vit bi phng php ny cha ng cu trc ca nhng i tng DataTable lu tr trong Dataset. Bn cng c th ly XML trong mt Dataset s dng phng thc GetXml() , tr v XML trong mt chui.
Bn c th c ni dung ca nhng i tng DataTable trong mt file XML vo trong mt Dataset s dng phng thc ReadXml() . Bn cng c th c m hnh cha trong mt mt file XML s dng phng thc ReadXmlSchema() . Ghi ch my ch phc v SQL cng cha chc nng XML dng sn rng ln, m bn s hc Trong Chng 16, "s dng H tr XML ca my ch phc v SQL ."
S DNG PHNG THC WriteXml():
Cho rng bn c mt i tng Dataset t tn MyDataSet. Gi thit rng myDataSet c mt DataTable cha nhng ct CustomerID, CompanyName, ContactName, V Address thuc hai hng u tin t bng Customers. M sau y cho thy iu ny
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 CustomerID, CompanyName, ContactName, Address " + "FROM Customers " + "ORDER BY CustomerID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); Console.WriteLine("Retrieving rows from the Customers table"); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close();
Bn c th vit ra ni dung ca myDataSet thnh mt file XML s dng phng thc WriteXml() . th d:
myDataSet.WriteXml("myXmlFile.xml");
m ny vit ra mt file XML c tn myXmlFile.xml, Nh trnh by trong Danh sch 10.9.
Danh sch 10.9: MYXMLFILE XML <?xml version="1.0" standalone="yes"?> <NewDataSet> <Customers> <CustomerID>ALFKI</CustomerID> <CompanyName>Alfreds Futterkiste</CompanyName> <ContactName>Maria Anders</ContactName> <Address>Obere Str. 57</Address> </Customers> <Customers> <CustomerID>ANATR</CustomerID> <CompanyName>Ana Trujillo Emparedados y helados</CompanyName> <ContactName>Ana Trujillo</ContactName> <Address>Avda. de la Constitucin 2222</Address> </Customers> </NewDataSet>
Nh bn c th thy, file ny cha nhng ct thuc nhng hng truy xut t bng Customers.
vi myXmlWriteMode l mt hng s t lp lit k System.Data.XmlWriteMode n ch nh vit d liu v m hnh XML nh th no Bng 10.8 cho thy nhng hng s nh ngha trong kiu lit k XmlWriteMode.
Hng s M t DiffGram Vit ra DataSet nh mt DiffGram, cha nhng gi tr ban u v nhng s thay i ti nhng gi tr ny lm chng lu hnh. Bn c th pht sinh mt DiffGram m ch cha nhng s thay i bi gi phng thc GetChanges() ca Dataset ca bn, v sau gi WriteXml(). IgnoreSchema Ch vit ra d liu trong Dataset, khng vit ra m hnh. IgnoreSchema l mc nh. WriteSchema Vit ra m hnh trong Dataset.
V d sau y cho thy s s dng hng s XmlWriteMode.WriteSchema myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);
M ny ghi ra mt file XML c tn myXmlFile2.xml, Nh trnh by trong Danh sch 10.10. Danh sch 10.10: MYXMLFILE2. XML <?xml version="1.0" standalone="yes"?> <NewDataSet> <xsd:schema id="NewDataSet" targetNamespace="" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft- com:xml-msdata"> <xsd:element name="NewDataSet" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="Customers"> <xsd:complexType> <xsd:sequence> <xsd:element name="CustomerID" type="xsd:string" minOccurs="0" /> <xsd:element name="CompanyName" type="xsd:string" minOccurs="0" /> <xsd:element name="ContactName" type="xsd:string" minOccurs="0" /> <xsd:element name="Address" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <Customers> <CustomerID>ALFKI</CustomerID> <CompanyName>Alfreds Futterkiste</CompanyName> <ContactName>Maria Anders</ContactName> <Address>Obere Str. 57</Address> </Customers> <Customers> <CustomerID>ANATR</CustomerID> <CompanyName>Ana Trujillo3 Emparedados y helados</CompanyName> <ContactName>Ana Trujillo</ContactName> <Address>Avda. de la Constitucin 2222</Address> </Customers> </NewDataSet>
Nh bn c th thy, file ny cha nh ngha m hnh cho nhng ct c dng trong pht biu nguyn thu SELECT, cng nh nhng gi tr ct cho nhng hng c truy xut.
S DNG PHNG THC WriteXmlSchema():
Bn c th vit ra m hnh ca myDataSet ti mt file XML s dng phng thc WriteXmlSchema() . Chng hn: myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");
M ny vit ra mt file XML c tn myXmlSchemaFile.xml, nh trnh by trong Danh sch 10.11. Danh sch 10.11: MYXMLSCHEMAFILE.XML <?xml version="1.0" standalone="yes"?> <xsd:schema id="NewDataSet" targetNamespace="" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="NewDataSet" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="Customers"> <xsd:complexType> <xsd:sequence> <xsd:element name="CustomerID" type="xsd:string" minOccurs="0" /> <xsd:element name="CompanyName" type="xsd:string" minOccurs="0" /> <xsd:element name="ContactName" type="xsd:string" minOccurs="0" /> <xsd:element name="Address" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
Nh bn c th thy, file ny cha nh ngha m hnh cho nhng ct c truy xut t bng Customers bi pht biu nguyn thu SELECT.
S DNG PHNG THC ReadXml()
Bn c th c ni dung ca mt file XML vo trong mt i tng Dataset s dng phng thc ReadXml() . Phng thc ny c nhng hng v nhng ct t file XML vo trong nhng i tng DataTable ca Dataset. Chng hn, pht biu sau y s dng phng thc ReadXml() c file XML myXmlFile.xml c vit trc bi phng thc WriteXml() : myDataSet.ReadXml("myXmlFile.xml");
vi myXmlReadMode l mt hng s t s lit k System.Data.XmlReadMode n ch nh cch c D liu v m hnh XML . Bng 10.9 cho thy nhng hng s nh ngha trong kiu lit k XmlReadMode. Bng 10.9: nhng thnh vin Lit k XmlReadMode Hng s M t Auto c file XML trong mt thi thch hp: Nu file XML cha mt DiffGram, th XmlReadMode c gn ti DiffGram. Nu Dataset cha mt m hnh hay file XML cha mt m hnh, th XmlReadMode c gn l ReadSchema. Nu DataSet khng cha mt m hnh v file XML khng cha mt m hnh, th XmlReadMode c gn l InferSchema. Auto l mc nh DiffGram c file XML nh mt DiffGram, cha nhng gi tr ban u v nhng thay i ti nhng gi tr lm chng lu hnh. ri nhng thay i ny c ng dng vo Dataset ca bn . n tng t nh gi phng thc Merge() ca mt Dataset trong nhng s thay i t mt Dataset c trn vi ci khc. Fragment c mt file XML c cha nhng on m hnh inline XDR nh nhng th c pht sinh bi vic thc thi nhng pht biu SELECT cha nhng mnh FOR XML . IgnoreSchema Ch c d liu trong Dataset, khng c m hnh. InferSchema Phn tch m hnh ca file XML bi vic kho st d liu c lu tr trong n. ReadSchema c m hnh t file XML ri ghi vo trong Dataset.
V d sau y cho thy s s dng hng s XmlReadMode.ReadSchema:
Danh sch 10.12 minh ha cch vit v c nhng file XML s dng ADO.NET.
Danh sch 10.12: WRITEANDREADXML.CS
/* WriteAndReadXml.cs illustrates how to write and read XML files */
using System; using System.Data; using System.Data.SqlClient;
class WriteAndReadXML { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 CustomerID, CompanyName, ContactName, Address " + "FROM Customers " + "ORDER BY CustomerID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); Console.WriteLine("Retrieving rows from the Customers table"); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close();
// use the WriteXml() method to write the DataSet out to an // XML file Console.WriteLine("Writing rows out to an XML file named " + "myXmlFile.xml using the WriteXml() method"); myDataSet.WriteXml("myXmlFile.xml");
Console.WriteLine("Writing schema out to an XML file named " + "myXmlFile2.xml using the WriteXml() method"); myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);
// use the WriteXmlSchema() method to write the schema of the // DataSet out to an XML file Console.WriteLine("Writing schema out to an XML file named " + "myXmlSchemaFile.xml using the WriteXmlSchema() method"); myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");
// use the Clear() method to clear the current rows in the DataSet myDataSet.Clear();
// use the ReadXml() method to read the contents of the XML file // into the DataSet Console.WriteLine("Reading rows from myXmlFile.xml " + "using the ReadXml() method"); myDataSet.ReadXml("myXmlFile.xml");
DataTable myDataTable = myDataSet.Tables["Customers"]; foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]); Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]); Console.WriteLine("ContactName = " + myDataRow["ContactName"]); Console.WriteLine("Address = " + myDataRow["Address"]); } } } u ra t chng trnh ny nh sau: Retrieving rows from the Customers table Writing rows out to an XML file named myXmlFile.xml using the WriteXml() method Writing schema out to an XML file named myXmlFile2.xml using the WriteXml() method Writing schema out to an XML file named myXmlSchemaFile.xml using the WriteXmlSchema() method Reading rows from myXmlFile.xml using the ReadXml() method CustomerID = ALFKI CompanyName = Alfreds Futterkiste ContactName = Maria Anders Address = Obere Str. 57 CustomerID = ANATR CompanyName = Ana Trujillo3 Emparedados y helados ContactName = Ana Trujillo Address = Avda. de la Constitucin 2222
V BN NHNG BNG V CT:
Trong chng 3, "Gii thiu ngn ng truy vn c cu trc (SQL) ," bn hc iu ny t kha As c dng ch nh mt b danh cho mt bng hay ct. V d sau y s dng t kha As t b danh cho ct CustomerID l MyCustomer v b danh bng Customers l Cust:
SELECT CustomerID AS MyCustomer, CompanyName, Address FROM Customers AS Cust WHERE CustomerID = 'ALFKI';
Hnh 10.2 cho thy nhng kt qu ca pht biu SELECT ny.
M sau y s dng pht biu SELECT ny c tr mt i tng Dataset c tn myDataSet:
Ch phng thc Fill() ch nh tn ca DataTable nh Customers, m c bit nh l tn ca DataTable ngun.
v bn mt DataTable trong Dataset ca bn, bn to ra mt i tng ca lp DataTableMapping s dng phng thc Add(); lp ny thuc namespace System.Data.Common , m bn cn phi ti vo trong chng trnh ca bn. V d sau y to ra mt i tng DataTableMapping c tn myDataTableMapping, v chuyn giao Customers v Cust (nh hai tham s) ti phng thc Add():
Ch rng phng thc Add() c gi thng qua thuc tnh TableMappings. Thuc tnh TableMappings tr li mt i tng ca lp TableMappingCollection .i tng ny l mt tp hp ca nhng i tng TableMapping, v bn s dng mt i tng TableMapping v bn tn ngun ny ti mt tn DataTable khc, bi vy, v d trc y v bn tn ngun ca Customers ti Cust.
Bn c th c bn ny s dng nhng thuc tnh ca SourceTable v DataSetTable ca myDataTableMapping. Chng hn:
Thuc tnh ColumnMappings tr li mt i tng ca lp DataColumnMappingCollection. i tng ny l mt tp hp ca nhng i tng DataColumnMapping. Bn s dng mt i tng DataColumnMapping v bn mt tn ct t c s d liu n mt tn ct d liu khc, do , v d trc y v bn tn ct CustomerID t c s d liu n tn MyCustomer DataColumn.
Danh sch 10.13 minh ha cch v bn nhng tn bng v ct s dng m trnh by trong mc ny.
Danh sch 10.13: MAPPINGS.CS
/* Mappings.cs illustrates how to map table and column names */
using System; using System.Data; using System.Data.SqlClient; using System.Data.Common;
class Mappings { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID AS MyCustomer, CompanyName, Address " + "FROM Customers AS Cust " + "WHERE CustomerID = 'ALFKI'"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close();
// create a DataTableMapping object DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Customers", "Cust");
// change the TableName property of the DataTable object myDataSet.Tables["Customers"].TableName = "Cust";
// display the DataSetTable and SourceTable properties Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable); Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);
// map the CustomerID column to MyCustomer myDataTableMapping.ColumnMappings.Add("CustomerID", "MyCustomer");
DataTable myDataTable = myDataSet.Tables["Cust"]; foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("CustomerID = " + myDataRow["MyCustomer"]); Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]); Console.WriteLine("Address = " + myDataRow["Address"]); } } } u ra t chng trnh ny nh sau:
C MT GI TR CT S DNG NHNG LP DATASET NH KIU D LIU MNH:
Mt i tng Dataset nh kiu mnh cho php bn c mt gi tr ct s dng mt thuc tnh cng tn vi ct. Chng hn, c gi tr CustomerID ca mt ct, bn c th s dng myDataRow.CustomerID hn l myDataRow[ " CustomerID "]. y l mt c tnh hay bi v trnh bin dch c th bt bt k li chnh t no trong tn ct trong thi gian bin tp hn l thi gian chy. Chng hn, nu bn ghi sai CustomerID l CustimerID, v li b bt ngay bi trnh bin dch.
c tnh khc ca mt Dataset nh kiu d liu mnh l khi bn lm vic vi n trong VS .NET, trnh cm ng thng minh t ng bt ra nhng thuc tnh v nhng phng thc ca Dataset ny khi bn ang g phm. v Bn c th chn thuc tnh hay phng thc t danh sch, hn l phi g mi th vo.
B su ca vic s dng mt Dataset nh kiu d liu mnh l bn phi thc hin vi cng vic ban u no to ra n trc khi bn c th s dng n. Nu nhng ct trong nhng bng c s d liu ca bn khng thng xuyn thay i , th bn cn phi cn trng s dng nhng i tng Dataset nh kiu d liu mnh. Mt khc, nu nhng bng c s d liu ca cc bn thng thay i, bn cn phi trnh chng bi v bn s phi to li Dataset nh kiu mnh gi cho n ng b vi nh ngha ca bng c s d liu.
Ghi nh: Bn s tm thy mt d n v d c b sung VS .NET cho mc ny trong th mc StronglyTypedDataSet. Bn c th m d n ny trong VS .Net bi chn File _ Open Project v m file WindowsApplication4.csproj . Bn s cn thay i thuc tnh ConnectionString ca i tng sqlConnection1 ni ti c s d liu Northwind SQL Server ca bn. Bn c th cng theo cng vi nhng ch dn trong mc ny bi vic sao chp th mc DataReader n th mc khc v s dng d n ny nh im xut pht ca bn.
TO MT LP DATASET NH KIU MNH:
Trong mc ny, bn s to ra mt lp Dataset nh kiu mnh m c dng truy nhp bng Customers. Nu bn theo nhng ch dn ny, m d n DataReader trong VS .NET v nhn p Form1.cs trong ca s Solution Explorer. Bn m ca s Solution Explorer bng cch chn View Solution Explorer.
Tip theo, chn File Add New Item. Chn Dataset t vng khung mu v g vo MyDataSet.xsd, nh trnh by trong hnh 10.3 .
Kch nt Open tip tc.
VS .NET s thm MyDataSet.xsd ti d n ca bn, nh trnh by trong hnh 10.4.
di v pha tri ca Hnh 10.4, bn ch hai tab: Dataset v XML. tab Dataset c trnh by theo mc nh v bn s dng n xem visual view ca Dataset ca bn. tab XML cho php bn xem File XML ca Dataset ca bn.
Tip theo, hy chc chn rng bn m ca s Explorer window; m ca s, chn View Server Explorer. M nt Data Connections v hoc s dng mt kt ni hin hu ti c s d liu Northwind hoc to ra mt kt ni mi bng cch nhn phi trn nt Data Connection v chn Add Connection t thc n s xung.
Nhn p i tng kt ni ca bn trong ca s Sever Explorer v tm xung ti bng, View hay th tc lu tr m bn mun s dng, v ri ko n vo form ca bn , bt u thc hin _ko bng Customers ln form ca bn.
Hnh 10.5 cho thy form khi bng Customers c thm.
Ghi nh : Bn c th thm nhiu bng vo form ca bn v nh ngha nhng quan h gia chng.
Tip theo, lu cng vic ca bn bi chn File Save All hay nhn Ctrl+ S trn bn phm .
D n ca bn by gi cha ng mt File XSD c tn MyDataSet.xsd, nh trnh by trong danh sch 10.14 . Bn c th xem file ny bi vic kch tab XML ti y ca ca s thit k XML.
Ch : file ny cha nhng chi tit ca nhng ct trong bng Customs.
D n ca bn cng cha mt lp mi c tn file l MyDataSet.cs, n cha lp Dataset nh kiu mnh ca bn. Bn c xem ni dung ca file ny s dng Ca s Solution Explorer . Bn m ca s Solution Explorer bi chn View Solution Explorer .
Ghi ch: xem file MyDataSet.cs, kch nt Show All Files trong ca s Solution Explorer.
Tip theo, bung nt bn di MyDataSet.xsd. Bn s thy MyDataSet.cs, nh trnh by trong Hnh 10.6 , v mt file c tn MyDataSet.xsx, n cha thng tin v cch trnh by cnh quan trc quan ca Dataset ca bn.
khi s _ m MyDataSet.cs bng cch nhn p n trong ca s Solution Explorer. xem m ca form ny bi vic chn View Code. Mt trong nhng lp c khai bo trong file ny l MyDataSet. Lp ny bt ngun t lp Dataset. Bn s s dng n trong mc tip theo to ra mt i tng Dataset nh kiu mnh truy nhp bng Customers .
S DNG LP DATASET NH KIU MNH:
Mt khi bn c lp MyDataSet nh kiu mnh , bn c th to ra mt i tng ca lp ny s dng m sau y:
MyDataSet myDataSet = new MyDataSet();
Bn cng c th to ra mt i tng bng DataTable nh kiu mnh s dng lp MyDataSet. CustomersDataTable v c tr n vi nhng hng t bng Customers. v d, bn c th t phng thc Form1_Load() ca form ca bn truy xut nhng gi tr ct CustomerID, CompanyName, V Address t bng Customers v gn chng vo mt iu khin ListView c tn listView1. lm iu ny, nhn p Form1.cs Trong ca s Solution Explorer , xem m, v t phng thc Form1_Load() nh sau:
Thuc tnh myDataRow.CustomerID tr li gi tr ct CustomerID, vn vn. Bin tp v chy form ca bn trong mt bc bi chn Debug Start Without Debugging. Hnh 10.7 cho thy kt qu s chy form.
Ghi nh: lp MyDataSet cha mt s phng thc cho php bn sa i nhng hng c ct gi trong mt i tng MyDataSet. Nhng phng thc ny bao gm NewCustomersRow(), AddCustomersRow(), FindByCustomerID(), V RemoveCustomersRow(). Bn cng c th kim tra liu mt gi tr ct cha ng mt gi tr null s dng nhng phng thc nh IsContactNameNull(), V Bn c th t mt ct vi gi tr null s dng nhng phng thc nh SetContactNameNull(). Bn s hc cch s dng nhng phng thc ny trong Chng 11.
TO MT I TNG DataAdapter S DNG VISUAL STUDIO .NET:
Trong mc ny, bn s hc cch to mt DataAdapter nh th no s dng Visual Studio .NET.
Ghi nh: Bn s tm thy mt d n VS .NET cho mc ny trong th mc DataAdapter. Bn c th m d n ny Trong VS .NET bi chn File Open Project v M File WindowsApplication4.csproj . Bn s cn thay i thuc tnh ConnectionString ca i tng sqlConnection1 kt ni ti c s d liu ca bn. Bn c th cng c th theo nhng ch dn trong mc ny bi vic sao chp th mc DataReader n th mc khc v s dng d n ny nh im xut pht ca bn.
M form ca bn bng cch nhn p Form1.cs trong ca s Solution Explorer. Tip theo, to mt i tng SqlDataAdapter bng cch ko mt i tng SqlDataAdapter t tab D liu ca hp Toolbox n form ca bn. Khi bn ko mt i tng SqlDataAdapter ti form , mt trnh Wizard Data Adapter Configuration khi chy (Cu hnh B tip hp D liu), nh trnh by trong Hnh 10.8.
Hnh 10.8: trnh hng dn to Cu hnh B tip hp D liu
Kch nt Next tip tc.
Bn by gi chn i tng kt ni c s d liu Bn mun s dng, hay Bn c th to ra mt i tng kt ni mi. chn c s d liu cn kt ni Northwind trong danh sch comboBox( Hay to ra mt kt ni mi nu bn cha c sn ), Nh trnh by trong Hnh 10.9.
Hnh 10.9: chn kt ni d liu ca bn
Kch nt Next tip tc.
Tip theo, bn t query type ca bn l "Use SQL statements." ( S dng nhng cu lnh SQL.) Nh bn c th thy t Hnh 10.10, bn t query type ca bn s dng nhng cu lnh SQL, to ra nhng th tc lu tr mi, hay s dng nhng th tc lu tr hin c. Nhng cu lnh SQL hay nhng th tc lu tr ri c s dng trong nhng thuc tnh SelectCommand, InsertCommand, UpdateCommand, V DeleteCommand ca i tng SqlDataAdapter ca bn. Bn s hc ba thuc tnh sau cng ny trong Chng 11; chng c dng chn, cp nht, v xa nhng hng.
Hnh 10.10: chn query type ca cc bn
Chc chn rng bn c chn "Use SQL statements", v kch nt Next tip tc.
Hnh 10.11: pht sinh nhng cu lnh SQL
Pht biu SELECT m bn nhp vo by gi c dng pht sinh nhng cu lnh SQL INSERT, UPDATE, and DELETE cng vi nhng nh x bng. Hnh 10.12 cho thy hp thoi cui cng ca wizard to "Cu hnh B tip hp D liu"(Data Adapter Configuration Wizard ).
Hnh 10.12:Hp thoi Cui cng ca wizard to Cu hnh B tip hp D liu
Kch nt Finish hon thnh wizard. Mt i tng SqlDataAdapter c tn sqlDataAdapter1, by gi c thm vo khay di form ca bn , nh trong Hnh 10.13.
Hnh 10.13: i tng SqlDataAdapter mi trong khay
Cnh bo: Bn cn t thuc tnh Connection ca SelectCommand trong i tng sqlDataAdapter1 ca cc bn ti i tng Kt ni (Connection) ca bn trc khi DataAdapter c th truy nhp c s d liu. Bn thc hin iu ny s dng ca s nhng thuc tnh bng cch duyt xung t SelectCommand n Connection. ri Bn kch danh sch x xung, chn Existing, ri chn i tng SqlConnection ca bn , n phi c tn l sqlConnection1 . ng thi kim tra thuc tnh ConnectionString ca i tng SqlConnection ca bn chc chn rng n c t ni ti c s d liu Northwind ca bn.
Ch : ba lin kt y ca ca s nhng thuc tnh Cho sqlDataAdapter1:
Configure Data Adapter : mi lin kt ny cho php bn ghi li Wizard nh hnh DataAdapter ca cc bn. Generate Dataset : mi lin kt ny cho php bn pht sinh mt i tng Dataset s dng tp hp thng tin cho DataAdapter ca bn. Bn s s dng mi lin kt ny trong mc k tip pht sinh mt Dataset mi. Preview Data : mi lin kt ny cho php bn xem trc d liu c tr li bi SelectCommand ca DataAdapter ca cc bn.
hy thoi mi kho st m sinh ra bi Wizard trong form ca cc bn cho i tng sqlDataAdapter1. Khi bn sn sng, chn File Save All.
Ghi nh : ng vi vng chy d n ca bn ngay, bi v bn s cn thm mt Dataset ,n s c c tr bi s dng DataAdapter ca bn trong mc k tip.
TO MT I TNG DATASET S DNG Visual Studio .NET:
Trong mc ny, bn s hc cch to ra mt Dataset s dng Visual.Studio .NET.
Ghi nh: Bn s tm thy mt d n v d c b sung Visual Studio .NET cho mc ny trong th mc Dataset. Bn c th m d n ny trong Visual Studio .NET bi chn File Open Project v m File WindowsApplication4.csproj . Bn cng c th theo nhng ch dn trong mc ny bng cch tip tc sa i bn sao chp ca d n DataReader m bn s dng trong mc trc .
Nu bn theo nhng ch dn ny, m bn sao ca d n DataReader m bn sa i trong mc trc , v m Form1.cs bng cch nhn p n trong ca s Solution Explorer . to ra mt i tng Dataset , bn c th thc hin mt trong s vic sau :
Ko mt i tng Dataset t tab Data ca Toolbox n form ca bn, v thm m vo form ca bn
in n s dng phng thc Fill() ca mt i tng DataAdapter. Kch lin kt Generate Dataset ti y ca ca s nhng thuc tnh ca DataAdapter ca bn. Bn c th nhn thy mi lin kt ny trong Hnh 10.13.
Bn s s dng hai bc, v bt u - kch lin kt Generate Dataset . hp thoi Generate Dataset xut hin, nh trnh by trong Hnh 10.14.
Hnh 10.14: hp thoi pht sinh Dataset
Kch nt Ok tip tc. i tng tp d liu mi c tn dataSet11 c thm vo khay di form ca bn, nh trong Hnh 10.15.
Hnh 10.15: i tng Dataset mi trong khay Bc tip theo ca bn l gn phng thc Form1_Load() ca form nh sau:
Ghi ch: Nh, xem m form ca bn, bn chn view code. Ri bn thay th phng thc Form1_Load() vi m trc y. v by gi bn c th bin tp v chy form ca bn. Hnh 10.16 cho thy s vn hnh ca form.
Hnh 10.16: form ang chy
TM LC: Trong chng ny, bn hc nhng chi tit v vic s dng nhng i tng Dataset lu tr nhng kt qu tr li t c s d liu. Nhng i tng Dataset cho php bn lu tr mt bn sao chp ca nhng bng v nhng hng t c s d liu, v bn c th lm vic vi bn sao cc b ny trong khi ngt kt ni vi c s d liu. Khng ging nhng i tng b cung cp c qun l(managed provider) nh nhng i tng SqlDataReader, nhng i tng Dataset l dng chung v bi vy lm vic vi bt k c s d liu no. Nhng i tng Dataset cng cho php bn c nhng hng trong bt k trt t no v sa i nhng hng.
Bn cng hc nhng chi tit v vic s dng mt i tng DataAdapter c nhng hng t c s d liu vo trong mt i tng Dataset. DataAdapter l b phn ca lp nh cung cp c qun l , v c ba lp DataAdapter : SqlDataAdapter, OleDbDataAdapter, V OdbcDataAdapter.
Bn s dng mt i tng DataAdapter di chuyn nhng hng gia i tng Dataset ca bn v c s d liu, v ng b ha bt k s thay i no Bn lm cho nhng hng lu tr cc b ca bn vi c s d liu. Chng hn, bn c th c nhng hng t c s d liu vo trong mt Dataset thng qua mt DataAdapter, Sa i nhng hng trong Dataset ca bn, v y nhng s thay i ti c s d liu thng qua i tng DataAdapter ca bn.
Trong Chng 11, bn s thy cch thc hin nhng thay i ti nhng hng trong mt Dataset v sau y nhng thay i ti c s d liu.
S DNG NHNG I TNG DATASET SA I D LIU:
Tng quan Trong chng 10, bn thy cch s dng mt Dataset ct gi mt bn sao ca nhng hng truy xut t c s d liu. Trong chng ny, bn s hc cch sa i nhng hng trong mt Dataset, v y nhng thay i ny ti c s d liu qua mt DataAdapter.
Nhng iu ni bt trong chng ny: Nhng lp DataTable, DataRow, v DataColumn Thm nhng s hn ch vo nhng i tng DataTable v DataColumn Tm kim, lc v sp xp nhng i tng DataRow trong mt DataTable Sa i nhng hng trong mt DataTable v y nhng s thay i ti c s d liu S dng nhng th tc lu tr thm, sa i, v loi b nhng hng t c s d liu S dng mt i tng CommandBuilder t ng pht sinh nhng cu lnh SQL Duyt tm nhng bin c ca DataAdapter v DataTable Gii quyt nhng s tht bi cp nht (update). S dng nhng giao dch vi mt Tp d liu Sa i d liu s dng mt Dataset nh kiu mnh.
LP DATATABLE:
Bn s dng mt i tng ca lp DataTable i din cho mt bng. Bn cng c th ct gi nhiu i tng DataTable trong mt Dataset. Bng 11.1 cho thy mt s nhng thuc tnh DataTable.
Bng 11.1: nhng thuc tnh DataTable THUC TNH KIU M T CaseSensitive bool Ly hay gn mt gi tr bool ch nh liu c phi nhng s so snh chui bn trong nhng i tng DataTable ph thuc kiu ch. ChildRelations DataRelationCollection ly tp hp ca nhng quan h (DataRelationCollection) n cho php s dn hng t mt bng cha n mt bng con. Mt DataRelationCollection gm c nhng i tng DataRelation. Columns DataColumnCollection Ly tp hp ca nhng ct (DataColumnCollection) n cha ng nhng i tng DataColumn i din cho nhng ct trong i tng DataTable . THUC TNH KIU M T Constraints ConstraintCollection c tp hp ca nhng s rng buc (ConstraintCollection) n cha ng nhng i tng rng buc i din cho nhng s rng buc kha chnh (UniqueConstraint) hay kha ph (ForeignKeyConstraint) trong i tng DataTable. DataSet DataSet ly Dataset m DataTable thuc v n. HasErrors bool tr li Gi tr mt bool m ch nh c nhng li trong bt k nhng hng trong DataTable hay khng. PrimaryKey DataColumn[] Ly hay gn mt mng ca nhng i tng DataColumn l nhng kha chnh cho DataTable. Rows DataRowCollection ly tp hp ca nhng hng (DataRowCollection) c cha nhng i tng DataRow c ct gi trong DataTable. TableName string Ly hay gn tn ca i tng DataTable.
Bng 11.2 trnh by mt s nhng phng thc DataTable. Phng thc Kiu tr v M t AcceptChanges() void hiu lc ha tt c nhng s thay i thc hin vi i tng DataTable t khi n c ti hay t ln cui cng phng thc AcceptChanges() c gi. Clear() void Loi b tt c cc hng t i tng DataTable. Clone() DataTable Sao chp cu trc ca nhng i tng DataTable v s tr v bn sao ny. Compute() object Tnh ton biu thc cho trn nhng hng hin thi thng qua iu kin lc. GetChanges() DataTable Qu ti . Tr li mt bn sao ca i tng DataTable t lc cui cng n c ti hay t ln cui cng phng thc AcceptChanges() c gi . GetErrors() DataRow[] Qu ti . ly mt bn sao ca tt c nhng i tng DataRow m c nhng li. LoadDataRow() DataRow Tm v cp nht mt i tng DataRow ch nh. Nu khng tm thy i tng thch ng , mt hng mi c to ra s dng nhng gi tr ch nh. NewRow() DataRow To ra mt i tng DataRow mi trong DataTable. RejectChanges() void hy tt c nhng s thay i thc hin vi i tng DataTable mt khi n c to ra hay t ln cui cng phng thc AcceptChanges() c gi. Select() DataRow[] Qu ti. Tr li mng ca nhng i tng DataRow c ct gi trong DataTable m ph hp vi chui lc c ch r. Bn cng c th thng qua mt chui vic cha nhng chi tit v vic sp nhng i tng DataRow.
Bng 11.3 trnh by mt s bin c DataTable. Bin c B s l bin c M t ColumnChanging DataColumnChangeEventHandler pht khi trc khi mt gi tr c thay i ca DataColumn c cp nht DataRow. ColumnChanged DataColumnChangeEventHandler pht khi sau khi mt gi tr DataColumn c thay i dc cp nht DataRow. RowChanging DataRowChangeEventHandler pht khi trc khi mt DataRow c thay i c c cp nht mt DataTable. RowChanged DataRowChangeEventHandler Pht khi sau khi mt DataRow c thay i c cp nht mt DataTable. RowDeleting DataRowChangeEventHandler Pht khi trc khi mt DataRow b xa t mt Bin c B s l bin c M t DataTable. RowDeleted DataRowChangeEventHandler Pht khi sau khi mt DataRow b xa t mt DataTable.
LP DATAROW:
Bn s dng mt i tng ca lp DataRow i din cho mt hng. Bn cng c th ct gi nhiu i tng DataRow mt DataTable. Bng 11.4 trnh by mt s thuc tnh DataRow.
Bng 11.4: nhng thuc tnh DataRow
Thuc tnh Kiu M t HasErrors bool Tr li mt gi tr bool cho bit liu c bt k nhng i tng DataColumn no trong DataRow c li hay khng. ItemArray object[] Ly hay gn tt c i tng DataColumn trong DataRow. RowState DataRowState Ly thng tin tnh trng DataRow hin thi. Trng thi c th l Added, Deleted, Detached (tch ra~ FT), Modified , hay Unchanged (Khng thay i). Trng thi ph thuc thao tc c thc hin trn DataRow v liu phng thc AcceptChanges() c gi v cp nht nhng s thay i hay khng. Table DataTable ly i tng DataTable m DataRow thuc vo.
Hng c to ra nhng khng l b phn ca mt i tng DataRowCollection; mt DataRow trong trng thi ny ngay lp tc sau khi n c to ra v trc khi n c thm vo mt tp hp, hay nu n c loi b khi mt tp hp.
Bng 11.5 trnh by mt s phng thc ca DataRow.
Phng thc Kiu tr v M t AcceptChanges() void Cp nht tt c nhng s thay i thc hin vi i tng DataRow t khi n c ti hay t ln cui cng phng thc AcceptChanges() c gi. BeginEdit() void Bt u mt son tho cho i tng DataRow. CancelEdit() void hy mt son tho cho i tng DataRow v tr li tnh trang nguyn bn ca n. ClearErrors() void Xa b bt k li no cho i tng DataRow. Delete() void Xa i tng DataRow. EndEdit() void kt thc mt son tho cho i tng DataRow v cp nht s thay i. GetChildRows() DataRow[] Qu ti . Tr v mt mng ca nhng i tng DataRow cha nhng hng con s dng i tng DataRelation c ch nh. GetColumnError() string Qu ti . Tr v mt m t li cho i tng DataColumn ch nh. GetColumnsInError() DataColumn[] Tr v mt mng ca nhng i tng DataColumn m c nhng li. GetParentRow() DataRow Qu ti. Tr v mt i tng DataRow c cha hng cha s dng i tng DataRelation c ch r. GetParentRows() DataRow[] Qu ti . Tr v mt mng ca nhng i tng DataRow c cha nhng hng cha s dng i tng DataRelation c ch r. Phng thc Kiu tr v M t IsNull() bool Qu ti. Tr v mt gi tr bool cho bit liu i tng DataColumn c ch r c cha mt gi tr null hay khng. RejectChanges() void hy tt c cc thay i thc hin vi i tng DataRow t khi phng thc AcceptChanges() c gi. SetNull() void Gn mt i tng DataColumnc ch r n mt gi tr null. SetParentRow() void Qu ti .Gn hng cha ti i tng DataRow c ch r.
LP DATACOLUMN:
Bn s dng mt i tng ca lp DataColumn i din cho mt ct. Bn cng c th ct gi nhiu i tng DataColumn trong mt DataRow. Bng 11.6 cho thy mt s thuc tnh DataColumn.
Bng 11.6: nhng thuc tnh DataColumn Thuc tnh Kiu M t AllowDBNull bool Ly hay gn mt gi tr bool cho bit liu nhng gi tr null c c cho php trong i tng DataColumn ny. gi tr mc nh l true. AutoIncrement bool ly hay gn mt gi tr bool cho bit liu i tng DataColumn c t ng tng dn gi tr ca ct cho nhng hng mi. gi tr mc nh l false. AutoIncrementSeed long Ly hay gn gi tr khi u cho i tng DataColumn. ch ng dng khi thuc tnh AutoIncrement c gn l true. mc nh l false. AutoIncrementStep long ly hay gn bc tng dn c dng. ch p dng khi thuc tnh tng t ng (AutoIncrement) c gn l true. mc nh l 1. Caption string Ly hay gn tiu cho ct. Tiu cho ct c hin th trn nhng form Windows . gi tr mc nh l null. ColumnName string Ly hay gn tn ca i tng DataColumn. ColumnMapping MappingType Ly hay gn MappingType ca i tng DataColumn .Ci ny xc nh cch mt DataColumn c lu gi trong mt ti liu XML s dng phng thc WriteXml() nh th no . DataType Type Ly hay gn kiu d liu .NET i din cho gi tr ct c ct gi trong i tng DataColumn. kiu d liu ny c th l i s Boole, Byte, Char, DateTime, Decimal(s thp phn), Double, Int16, Int32, Int64, SByte, Single, string (chui), TimeSpan, UInt16, Hay UInt64. DafaultValue object Ly hay gn gi tr mc nh cho DataColumn khi nhng hng mi c to ra. Khi thuc tnh AutoIncrement (s tng t ng) c gn l true, gi tr mc nh khng c s dng. MaxLength int Ly hay gn chiu di cc i ca text ( vn bn) c ct gi trong mt i tng DataColumn . gi tr mc nh l -1. Ordinal int Ly s v tr ca i tng DataColumn (0 l i tng u tin). ReadOnly bool Ly hay gn mt gi tr bool cho bit liu c phi i tng DataColumn c th c thay i mt khi n c thm vo mt DataRow. mc nh l false. Table DataTable Ly DataTable m i tng DataColumn thuc v n. Unique bool Ly hay gn mt gi tr bool cho bit liu c phi nhng gi tr DataColumn trong mi i tng DataRow l duy nht. mc nh l false.
Bn s thy nhng s dng mt s thuc tnh , phng thc v nhng s kin ny sau trong chng ny.
THM NHNG HN CH VO NHNG I TNG DATATABLE V DATACOLUMN
Nh bn bit, mt i tng Dataset c dng ct gi mt bn sao ca mt tp con ca c s d liu. Chng hn, bn c th ct gi mt bn sao ca nhng hng t c s d liu vo trong mt Dataset, vi mi bng c i din bi mt i tng DataTable. Mt DataTable lu tr nhng ct trong nhng i tng DataColumn.
Ngoi vic ct gi nhng hng c truy xut t mt bng c s d liu, bn cng c th thm nhng hn ch vo mt DataTable v nhng i tng DataColumn ca n. iu ny cho php bn m hnh ha nhng s hn ch nh nhau t ln nhng bng c s d liu v nhng ct trong DataTable ca bn v nhng i tng DataColumn. Chng hn, bn c th thm nhng s rng buc sau y Ti mt DataTable: Unique (gi tr duy nht) Primary key (kha chnh) Foreign key (kha ph) Ngoi ra, bn c th thm nhng s hn ch sau y ti mt DataColumn:
Liu c phi ct c th chp nhn mt gi tr null m bn ct gi trong thuc tnh AllowDBNull ca DataColumn.
Bt k thng tin v s tng t ng no m bn ct gi trong thuc tnh AutoIncrement, AutoIncrementSeed, v AutoIncrementStep ca DataColumn. Bn gn nhng thuc tnh ny khi thm nhng hng ti mt DataTable vi mt bng c s d liu tng ng c cha mt ct kha chnh. Ct ProductID ca bng Products l mt v d ca mt ct nhn dng.
Ghi ch: ADO.NET s khng t ng pht sinh nhng gi tr cho nhng ct kha chnh trong mt hng mi. Ch c s d liu c th lm iu . Bn phi c gi tr kha chnh c pht sinh cho ct t c s d liu. Bn s thy cch lm iu nh th no sau trong nhng mc " truy xut nhng gi tr kha chnh mi " V " s dng nhng th tc lu tr Thm, Sa i, v Loi b nhng hng t C s d liu.". ng thi, nu bng c s d liu ca bn cha nhng ct c gn mt gi tr ngm nh, bn cn phi c gi tr t c s d liu. nh th tt hn s thit t thuc tnh DefaultValue ca mt DataColumn v nu gi tr ngm nh gn trong nhng thay i nh ngha bng c s d liu , bn c th chn gi tr mi t c s d liu hn l phi thay i m ca bn.
Chiu di cc i ca mt chui hay gi tr ct k t m bn ct gi trong thuc tnh MaxLength ca DataColumn. Liu c phi ct l ch c- m bn ct gi trong thuc tnh ReadOnly ca DataColumn. Liu c phi gi tr ct l duy nht- m bn ct gi trong thuc tnh Unique ca DataColumn.
Bng cch thm nhng s hn ch ny ln pha trc, bn ngn nga d liu xu thm vo Dataset ca bn bt u vi n. Nhng tr gip ny gim thiu nhng li khi th y nhng thay i trong Dataset ca bn ti c s d liu. Nu mt ngi s dng chng trnh ca bn c thm d liu m xm phm mt s hn ch, chng s gy ra mt ngoi l . Bn c th bt ngoi l ny trong chng trnh ca bn v hin th mt thng bo li vi nhng chi tit. v ngi s dng c th thay i d liu h c thm vo chnh nh vn .
Bn cng cn nh ngha mt kha chnh trc khi bn c th tm , lc, v phn loi nhng i tng DataRow trong mt DataTable. Bn s hc lm iu nh th no sau trong mc " Tm kim, Lc v phn loi nhng hng trong mt DataTable."
Mo nh: Thm nhng s rng buc gy ra mt s gim cp thc thi khi bn gi phng thc fill() ca mt DataAdapter. y l bi v nhng hng c truy xut c kim tra chng li nhng s rng buc ca bn trc khi chng c thm vo Dataset ca bn. do Bn cn phi t thuc tnh EnforceConstraints ca Dataset ca bn l false trc khi gi phng thc Fill() . ri Bn gn EnforceConstraints tr li ga tr mc nh true sau khi gi phng thc Fill().
Bn c th s dng mt trong nhng cch sau thm nhng s hn ch vo nhng i tng DataTable v DataColumn. T bn thm nhng s hn ch bi vic gn nhng thuc tnh ca nhng i tng DataTable v DataColumn ca bn. iu ny dn n s thc hin m nhanh nht
Gi phng thc FillSchema() ca DataAdapter ca bn sao chp thng tin m hnh t c s d liu n Dataset ca bn. iu ny c tr nhng thuc tnh ca nhng i tng DataTable v nhng i tng DataColumn ca chng mt cch t ng.
Bn s hc nhng chi tit ca c hai k thut ny trong nhng mc sau .
T THM NHNG HN CH BNG TAY:
Bn c th thm nhng s hn ch vo nhng i tng DataTable v DataColumn ca bn s dng nhng thuc tnh ca i tng DataTable v DataColumn.
Th d, gi thit bn c mt i tng Dataset c tn myDataSet c cha ba i tng DataTable t tn l Products, Orders, v Details c c tr s dng m sau y:
Kha chnh cho bng Products l ct ProductID; kha chnh cho bng Orders l ct OrderID; v kha chnh cho bng Order Details c to ra t c hai ct OrderID ln ProductID.
Ghi ch : Bn phi bao gm tt c nhng ct ca kha chnh ca bng c s d liu trong cu truy vn ca bn nu Bn mun nh ngha mt kha chnh trn nhng ct trong DataTable ca bn.
Trong nhng mc sau y, bn s hiu lm th no
Thm nhng s rng buc vo nhng i tng DataTable : Products, Orders v Order Details. Hn ch nhng gi tr c t trong nhng i tng DataColumn ca DataTable Produsts.
THM NHNG RNG BUC VO NHNG I TNG DATATABLE:
Trong mc ny, bn s thy cch thm nhng s rng buc vo nhng i tng DataTable . c bit, bn s thy cch thm nhng s rng buc kha chnh vo nhng i tng DataTable : Products,Orders, v Order Details. Mt s rng buc kha chnh tht s c thc hin nh mt s rng buc duy nht. Bn cng s thy cch thm nhng s rng buc kha ph t nhng i tng DataTable Order Detail n Products v Orders .
Nhng s rng buc c ct gi trong mt i tng ConstraintCollection m ct gi nhng i tng rng buc(Constraint). Bn truy nhp ConstraintCollection s dng nhng thuc tnh rng buc(Constraint) ca i tng DataTable. thm mt i tng rng buc mi Ti ConstraintCollection, Bn gi phng thc Add() thng qua thuc tnh Constraints. Phng thc Add() cho php bn thm nhng s rng buc kha chnh v kha ph vo mt DataTable. V mt rng buc kha chnh c thc hin nh mt rng buc duy nht, bn cng c th s dng phng thc Add() thm mt rng buc kha chnh vo mt DataTable. Bn s thy cch s dng phng thc Add() tip sau y .
Bn c th cng thm mt s rng buc kha chnh vo mt i tng DataTable bi thit t thuc tnh PrimaryKey ca n, m bn gn ti mt mng ca nhng i tng DataColumn thuc kha chnh . Mt mng c yu cu bi v kha chnh ca mt bng c s d liu c th c to ra t nhiu ct. Nh bn s thy trong nhng v d, iu ny n gin hn so vi s dng phng thc Add() thm mt rng buc kha chnh. ________________________________________________________________________________________ Gi phng thc Fill() ca mt DataAdapter nhiu hn mt ln
phng thc Fill() truy xut tt c nhng hng t bng c s d liu, nh ch r trong thuc tnh SelectCommand ca i tng DataAdapter ca cc bn. Nu bn thm mt kha chnh ti DataTable ca bn, ri gi phng thc Fill() hn mt ln s t nhng hng c truy xut trong DataTable ca bn v xa b bt k hng hin hu no vi nhng gi tr ct kha chnh ph hp c trong DataTable ca bn.
Nu bn khng thm mt kha chnh Ti DataTable ca bn , ri gi phng thc Fill() nhiu hn mt ln s ch n gin l thm tt c nhng hng c truy xut vo DataTable ca bn ln na, s trng lp nhng hng s sy ra.
v y l l do khc thm mt s rng buc kha chnh vo DataTable ca bn bi v bn khng mun c nhng hng trng lp. ________________________________________________________________________________________
THM MT KHA CHNH VO DATATABLE PRODUCTS
Chng ta hy xem xt vic thm mt kha chnh vo DataTable Products. u tin, v d sau y to ra mt i tng DataTable tn productsDataTable v gn n n DataTable Products truy xut t myDataSet:
By gi, kha chnh ca bng c s d liu Products l ct ProductID; bi vy, bn cn t thuc tnh PrimaryKey ca productsDataTable ti mt mng cha i tng DataColumn ProductID. V d sau y cho thy cch thc hin iu ny . N to ra mt mng nhng i tng DataColumn tn productsPrimaryKey v khi to ng thi gn n ti ct ProductID ca productsDataTable, ri t thuc tnh PrimaryKey ca productsDataTable ti mng: Khi to i tng productsPrimaryKey (ct d liu) DataColumn[] productsPrimaryKey = new DataColumn[] { gn ct ProductID thuc bng productsDataTable vo i tng productsPrimaryKey productsDataTable.Columns["ProductID"] }; gn productsPrimaryKey thuc tnh PrimaryKey ca ProductsDataTable productsDataTable.PrimaryKey = productsPrimaryKey;
Khi bn t thuc tnh PrimaryKey ca mt DataTable, nhng thuc tnh AllowDBNull v Unique ca i tng DataColumn t ng c thay i nh sau:
Thuc tnh AllowDBNull c thay i ti false cho bit DataColumn khng th chp nhn mt gi tr null. Thuc tnh Unique c thay i l true v cho bit gi tr DataColumn trong mi DataRow phi l duy nht.
Do , trong v d trc y, thuc tnh AllowDBNull v Unique ca ct d liu ProductID t ng c thay i ti gi tr false v true, tng ng.
THM MT KHA CHNH VO BNG D LIU(DATATABLE) ORDERS:
V d sau y t thuc tnh PrimaryKey ca DataTable -Orders ti OrderID DataColumn:
myDataSet.Tables["Orders"].PrimaryKey = new DataColumn[] { myDataSet.Tables["Orders"].Columns["OrderID"] };
Ch : Ti phi s dng mt pht biu trong v d ny cho ngn gn hn v d trc y.
Bn cng c th s dng Thm phng thc Add() thm mt kha unique, primary , hay foreign vo mt DataTable. phng thc Add() c ti nh sau:
void Add(Constraint myConstraint) // adds any constraint void Add(string constraintName, DataColumn myDataColumn,bool isPrimaryKey) // adds a primary key or unique constraint void Add(string constraintName, DataColumn parentColumn,DataColumn childColumn) // adds a foreign key constraint void Add(string constraintName, DataColumn[] myDataColumn, bool isPrimaryKey) // adds a primary key or unique constraint void Add(string cosntraintName, DataColumn[] parentColumns,DataColumn[] childColumns) // adds a foreign key constraint
VI: constraintName: l tn bn mun gn ti s rng buc ca cc bn. isPrimaryKey :cho bit liu c phi rng buc l mt rng buc kha chnh hay ch l mt rng buc duy nht bnh thng.
V d sau y s dng phng thc Add() thm mt s rng buc kha chnh vo DataTable Products:
V d ny thc hin tng t nh v d trc y l thm s rng buc kha chnh s dng thuc tnh PrimaryKey. Ch tham s cui cng ti phng thc Add() c t l true, n cho bit s rng buc thuc mt kha chnh.
Ngoi ra, nu bn c mt ct khng l kha chnh nhng c gi tr l duy nht, bn c th thm mt i tng UniqueConstraint vo ConstraintsCollection. Chng hn:
UniqueConstraint myUC = new UniqueConstraint(myDataTable.Columns["myColumn"]); myDataTable.Constraints.Add(myUC);
THM MT KHA CHNH VO BNG D LIU ORDER DETAILS:
Chng ta hy xem xt mt v d v thit t thuc tnh PrimaryKey cho bng d liu Order Details . Kha chnh cho bng Order Details c to ra t nhng ct OrderID v ProductID, v v d sau y cho thy s thit t thuc tnh PrimaryKey ca bng d liu Order Details ti hai ct ny:
Mt iu cn phi nh khi thm nhng s rng buc vo mt DataTable l n ch bit v nhng hng bn ct gi trong n; n khng bit v bt c hng no khc c ct gi trong bng c s d liu thc t. hiu ti sao y li l mt vn , xem xt chui s kin sau y n bao gm nhng kha chnh:
1. Bn thm mt s rng buc kha chnh vo mt DataTable. 2. Bn truy xut mt tp con ca nhng hng t mt bng c s d liu v ct gi chng trong DataTable ca bn. 3. Bn thm mt DataRow mi vo DataTable ca bn vi mt gi tr kha chnh khng phi c dng trong tp con ca nhng hng c truy xut vo trong DataTable ca bn trong nhng bc trc - nhng gi tr kha chnh c s dng trong mt hng trong bng c s d liu. DataRow mi ca bn c thm vo DataTable khng c bt k li no mc d bn thm mt s rng buc kha chnh vo DataTable ca bn trong bc 1. DataRow mi ca bn c thm vo mt cch thnh cng bi v DataTable ch bit v nhng hng c ct gi trong n, khng phi l nhng hng khc c ct gi trong bng c s d liu m khng c truy xut trong bc 2. 4. Bn th y DataRow mi ti c s d liu, nhng bn nhn mt SqlException nhng trng thi Bn xm phm s rng buc kha chnh trong bng c s d liu. y l bi v mt hng trong bng c s d liu s dng gi tr kha chnh.
Bn cn nh n vn ny khi thm nhng hng ti mt DataTable, m bn s thy cch thc hin khng lu sau y.
iu gm thm nhng s rng buc kha chnh vo nhng i tng DataTable. Tip theo, bn s thy cch thm nhng s rng buc kha ph nh th no .
THM NHNG RNG BUC VO BNG D LIU ORDER DETAILS:
Trong mc ny, bn s thy cch thm mt rng buc kha ph vo DataTable -Order Details nh th no . lm iu ny bn s dng phng thc Add() thng qua thuc tnh Constraints ca DataTable.
V d sau y thm mt rng buc kha ph t DataColumn(ct d liu) -OrderID ca DataTable(bng d liu) -Order Details n DataColumn OrderID ca DataTable- Orders :
Ghi ch: Ch l DataColumn cha(OrderID ca Orders) c nh ngha trc DataColumn con (OrderID ca Order Details).
V d k tip thm mt rng buc kha ph t DataColumn ProductID ca DataTable Order Details n DataColumn ProductID ca DataTable Products :
myDataSet.Tables["Order Details"].Constraints.Add( "Foreign key constraint to ProductID DataColumn of the " + "Products DataTable", myDataSet.Tables["Order Details"].Columns["ProductID"], myDataSet.Tables["Products"].Columns["ProductID"] );
iu bao gm nhng rng buc vo nhng i tng DataTable. Tip theo, bn s thy cch thm nhng hn ch vo nhng i tng DataColumn nh th no
THM NHNG HN CH VO NHNG I TNG DATACOLUMN:
Trong mc ny, bn s thy cch thm nhng hn ch vo nhng i tng DataColumn c ct gi mt DataTable nh th no. c bit, bn s thy cch thit t cho nhng thuc tnh AllowDBNull, AutoIncrement(S tng t ng), AutoIncrementSeed, AutoIncrementStep, ReadOnly, V Unique (duy nht ) ca DataColumn - ProductID ca DataTable - Prtoducts. Bn cng s thy cch t thuc tnh MaxLength ca DataColumn - ProductName ca DataTable - Products nh th no.
Ct ProductID ca bng c s d liu Products l mt ct nhn dng (kha chnh). seed l gi tr ban u v step (bc tng) l s tng thm gi tr n s sau cui v c hai (seed v step)c gn l 1 cho ProductID. Do nhng gi tr nhn dng ProductID s l 1, 2, 3, vn vn.
Mo nh: Khi bn gn nhng thuc tnh AutoIncrementSeed ln AutoIncrementStep cho mt DataColumn tng ng vi mt ct nhn dng c s d liu, bn cn phi lun lun gn chng ti -1. vi cch ny, khi bn gi phng thc Fill() , ADO.NET s t ng tnh nhng gi tr gn cho AutoIncrementSeed v AutoIncrementStep, da vo nhng gi tr truy xut c t c s d liu, v bn khng cn phi tnh n nhng gi tr ny.
M sau y thit t nhng thuc tnh ca DataColumn - ProductID :
Lit k 11.1 trnh by nhng m v d s dng trong mc ny v mt mc trc. Ch chng trnh ny cng trnh by nhng thuc tnh ColumnName v DataType ca nhng i tng DataColumn trong mi DataTable. Thuc tnh ColumnName cha tn ca DataColumn, v DataType cha kiu d liu .NET thng i din cho gi tr ct c ct gi trong DataColumn.
Danh sch 11.1: ADDRESTRICTIONS.CS
/* AddRestrictions.cs illustrates how to add constraints to DataTable objects and add restrictions to DataColumn objects */
using System; using System.Data; using System.Data.SqlClient;
class AddRestrictions { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// set the PrimaryKey property for the Products DataTable // to the ProductID column DataTable productsDataTable = myDataSet.Tables["Products"]; DataColumn[] productsPrimaryKey = new DataColumn[] { productsDataTable.Columns["ProductID"] }; productsDataTable.PrimaryKey = productsPrimaryKey;
// set the PrimaryKey property for the Orders DataTable // to the OrderID column myDataSet.Tables["Orders"].PrimaryKey = new DataColumn[] { myDataSet.Tables["Orders"].Columns["OrderID"] };
// set the PrimaryKey property for the Order Details DataTable // to the OrderID and ProductID columns myDataSet.Tables["Order Details"].Constraints.Add( "Primary key constraint on the OrderID and ProductID columns", new DataColumn[] { myDataSet.Tables["Order Details"].Columns["OrderID"], myDataSet.Tables["Order Details"].Columns["ProductID"] }, true );
// add a foreign key constraint on the OrderID column // of Order Details to the OrderID column of Orders ForeignKeyConstraint myFKC = new ForeignKeyConstraint( myDataSet.Tables["Orders"].Columns["OrderID"], myDataSet.Tables["Order Details"].Columns["OrderID"] ); myDataSet.Tables["Order Details"].Constraints.Add(myFKC); // add a foreign key constraint on the ProductID column // of Order Details to the ProductID column of Products myDataSet.Tables["Order Details"].Constraints.Add( "Foreign key constraint to ProductID DataColumn of the " + "Products DataTable", myDataSet.Tables["Products"].Columns["ProductID"], myDataSet.Tables["Order Details"].Columns["ProductID"] );
// set the AllowDBNull, AutoIncrement, AutoIncrementSeed, // AutoIncrementStep, ReadOnly, and Unique properties for // the ProductID DataColumn of the Products DataTable DataColumn productIDDataColumn = myDataSet.Tables["Products"].Columns["ProductID"]; productIDDataColumn.AllowDBNull = false; productIDDataColumn.AutoIncrement = true; productIDDataColumn.AutoIncrementSeed = -1; productIDDataColumn.AutoIncrementStep = -1; productIDDataColumn.ReadOnly = true; productIDDataColumn.Unique = true;
// set the MaxLength property for the ProductName DataColumn // of the Products DataTable myDataSet.Tables["Products"].Columns["ProductName"].MaxLength = 40;
// display the details of the DataColumn objects for // the DataTable objects foreach (DataTable myDataTable in myDataSet.Tables) { Console.WriteLine("\n\nReading from the " + myDataTable + "DataTable:\n");
// display the primary key foreach (DataColumn myPrimaryKey in myDataTable.PrimaryKey) { Console.WriteLine("myPrimaryKey = " + myPrimaryKey); }
// display some of the details for each column foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine("\nmyDataColumn.ColumnName = " + myDataColumn.ColumnName); Console.WriteLine("myDataColumn.DataType = " + myDataColumn.DataType);
Thm nhng hn ch bi vic gi phng thc FillSchema() ca i tng DataAdapter
Thay v thm nhng s hn ch bi chnh bn , bn c th thm chng bng cch gi phng thc FillSchema() ca DataAdapter ca bn. Phng thc FillSchema() thc hin nhng iu sau:
Sao chp thng tin m hnh t c s d liu. To ra nhng i tng DataTable trong Dataset ca bn nu chng cha tn ti. Thm nhng rng buc vo nhng i tng DataTable. t nhng thuc tnh ca nhng i tng DataColumn ph hp.
Nhng thuc tnh ca nhng i tng DataColumn thit t bi FillSchema() bao gm :
Tn DataColumn -c ct gi trong thuc tnh ColumnName. kiu d liu DataColumn .NET - c ct gi trong thuc tnh DataType. Chiu di cc i ca mt kiu d liu di bin c ct gi trong thuc tnh MaxLength. Cho bit DataColumn c th chp nhn mt gi tr null - c ct gi trong thuc tnh AllowDBNull. Cho bit gi tr DataColumn phi l duy nht - c ct gi trong thuc tnh Unique. Bt k thng tin tng t ng no - c ct gi trong nhng thuc tnh AutoIncrement (tng t ng), AutoIncrementSeed(gi tr u), V AutoIncrementStep(buc tng).
phng thc FillSchema() cng s xc nh liu c phi DataColumn l b phn ca mt kha chnh v lu tr thng tin ny trong thuc tnh Primarykey ca DataTable.
Cnh bo: Phng thc FillSchema() khng t ng thm nhng i tng ForeignKeyConstraint vo nhng i tng DataTable. Khng c g khin n truy xut nhng hng thc t t c s d liu; n ch khi phc thng tin m hnh.
phng thc FillSchema() b qu ti, vi phin bn thng s dng nht ca phng thc ny nh sau:
mySchemaType : ch r bn cch mun x l bt k nh x m hnh hin hu nh th no.
Bn gn mySchemaType ti mt trong s nhng hng s c nh ngha trong lp lit k System.Data.SchemaType. Bng 11.7 cho thy rng nhng hng s nh ngha trong lp lit k SchemaType.
Bng 11.7: nhng thnh vin Lit k SchemaType Hng s M t Mapped p dng cho bt k nh x bng hin hu no vo m hnh u vo v nh hnh DataSet vi m hnh bin i. y l hng s bn cn phi s dng cch in hnh. Source b qua bt k nh x bng no v nh hnh Dataset khng c bt k s bin i no.
Chng ta hy xem xt mt v d c cha mt lnh gi ti phng thc FillSchema() . Ch lnh gi s dng hng s SchemaType.Mapped p dng cho bt k nh x bng hin hu no:
S gi ti phng thc FillSchema() s sao chp thng tin m hnh t nhng bng Products, Orders, v Order Details ti myDataSet, thit t thuc tnh PrimaryKey ca mi DataTable v nhng thuc tnh ca nhng i tng DataColumn cch ph hp.
Danh sch 11.2 cho thy s s dng ca phng thc FillSchema().
/* FillSchema.cs illustrates how to read schema information using the FillSchema() method of a DataAdapter object */
using System; using System.Data; using System.Data.SqlClient;
class FillSchema { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// display the details of the DataColumn objects for // the DataTable objects foreach (DataTable myDataTable in myDataSet.Tables) { Console.WriteLine("\n\nReading from the " + myDataTable + "DataTable:\n");
// display the primary key foreach (DataColumn myPrimaryKey in myDataTable.PrimaryKey) { Console.WriteLine("myPrimaryKey = " + myPrimaryKey); }
// display the constraints foreach (Constraint myConstraint in myDataTable.Constraints) { Console.WriteLine("myConstraint.IsPrimaryKey = " + ((UniqueConstraint) myConstraint).IsPrimaryKey); foreach (DataColumn myDataColumn in ((UniqueConstraint) myConstraint).Columns) { Console.WriteLine("myDataColumn.ColumnName = " + myDataColumn.ColumnName); } }
// display some of the details for each column foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine("\nmyDataColumn.ColumnName = " + myDataColumn.ColumnName); Console.WriteLine("myDataColumn.DataType = " + myDataColumn.DataType);
Console.WriteLine("myDataColumn.AllowDBNull = " + myDataColumn.AllowDBNull); Console.WriteLine("myDataColumn.AutoIncrement = " + myDataColumn.AutoIncrement); Console.WriteLine("myDataColumn.AutoIncrementSeed = " + myDataColumn.AutoIncrementSeed); Console.WriteLine("myDataColumn.AutoIncrementStep = " + myDataColumn.AutoIncrementStep); Console.WriteLine("myDataColumn.MaxLength = " + myDataColumn.MaxLength); Console.WriteLine("myDataColumn.ReadOnly = " + myDataColumn.ReadOnly); Console.WriteLine("myDataColumn.Unique = " + myDataColumn.Unique); } } } } The output from this program is as follows: Reading from the Products DataTable:
Mi hng trong mt DataTable c ct gi trong mt i tng DataRow, v trong mc ny bn s hc cch tm , lc, v phn loi nhng i tng DataRow mt DataTable nh th no.
TM MT DATAROW TRONG MT DATATABLE:
tm mt DataRow trong mt DataTable, bn theo nhng bc sau:
1. Truy xut nhng hng t c s d liu vo trong DataTable ca bn. 2. Thit t thuc tnh PrimaryKey ca DataTable ca cc bn. 3. Gi phng thc Find() ca DataTable ca bn , thng qua gi tr ct kha chnh ca DataRow bn cn tm.
Chng hn, m sau y thc hin nhng bc 1 v 2 trong danh sch ny, truy xut 10 hng u tin t bng Products v thit t thuc tnh Primarykey ti ct d liu ProductID:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 10 ProductID, ProductName " + "FROM Products " + "ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Products"); mySqlConnection.Close(); DataTable productsDataTable = myDataSet.Tables["Products"]; productsDataTable.PrimaryKey = new DataColumn[]{productsDataTable.Columns["ProductID"]};
Tip theo, v d sau y thc hin bc 3: gi phng thc Find() truy xut DataRow c ProductID l 3 t productsDataTable
Ch : phng thc Find() c gi thng qua thuc tnh nhng hng ca productsDataTable. Thuc tnh nhng hng tr li mt i tng ca lp DataRowCollection .
Nu kha chnh cho bng c s d liu gm c nhiu ct, th bn c th thng qua mt mng ca nhng i tng chuyn ti phng thc Find(). Chng hn, nhng kha chnh ca bng Order Details c to ra t nhng ct OrderID v ProductID. Gi thit bn thc hin nhng bc 1 v 2 v truy xut nhng hng t nhng bng Order Details vo trong mt i tng DataTable c tn orderDetailsDataTable, Ri theo v d sau y truy xut DataRow vi mt OrderID v ProductID c gi tr 10248 v 11 tng ng.
object[] orderDetails = new object[] {10248,11}; DataRow orderDetailDataRow= orderDetailsDataTable.Row.Find(orderdetail);
S LC V PHN LAI NHNG I TNG DATAROW MT DATATABLE:
lc v phn loi nhng i tng DataRow trong mt DataTable, bn s dng phng thc Select() ca DataTable ca bn. Phng thc Select() c ti nh sau:
Vi filterExpression : ch nh nhng hng chn. sortExpression : ch r nhng hng c la chn s c sp xp nh th no. myDataViewRowState : ch nh trng thi ca nhng hng chn. Bn gn myDataViewRowState ti mt trong s nhng hng s c nh ngha trong lp lit k System.Data.DataViewRowState . Bng 11.8 trnh by nhng hng s ny.
Bng 11.8: nhng thnh vin Lit k DataViewRowState
Hng s M t Added Mt hng mi. CurrentRows Nhng hng hin thi, m bao gm nhng hng Unchanged (khng thay i), Added( thm vo), v ModifiedCurrent ( thay i) . Deleted Mt hng xa ModifiedCurrent Mt hng hin thi c sa i. ModifiedOriginal Hng nguyn bn trc khi n c sa i. None Khng ph hp vi bt k hng no ca nhng hng trong DataTable. OriginalRows Nhng hng nguyn bn, m bao gm nhng hng khng thay i v b xa . Unchanged Mt hng m khng c thay i.
Chng ta hy xem xt vi v d s dng phng thc Select() .
V d sau y gi phng thc Select() khng c nhng tham s, n tr li tt c cc hng trong DataTable khng c bt k s lc hay sp xp no
Nh bn c th thy t nhng v d trc y, nhng biu thc lc v phn lai th tng t nh mnh WHERE v ORDER BY trong pht biu SELECT. Do bn c th s dng nhng biu thc mnh m trong nhng lnh gi ca bn ti phng thc Sort() . v d, bn c th s dng nhng tan t so snh AND, OR, NOT, IN, LIKE, nhng ton t s hc, nhng k t i din, v nhng hm tng th trong nhng biu thc lc ca bn.
Ghi ch : cho nhng chi tit y v cch s dng nhng biu thc lc, tham chiu ti thuc tnh DataColumn.Expression trong ti liu trc tuyn .NET.
V d sau y s dng ton t LIKE v k t i din (%)- ph hp vi bt k s lng k t no- lc nhng hng c ProductName bt u vi 'cha'. V d cng phn loi v sp xp nhng hng vi gi tr ProductID gim dn v ProductName tng dn .
productDataRows = productsDataTable.Select("ProductName LIKE 'Cha%'", "ProductID DESC, ProductName ASC");
Ch : chui Cha% c t trong nhng trch dn n ('Cha%'), m bn phi thc hin cho tt c cc k t chui. Ghi nh : Bn cng c th s dng mt i tng DataView lc v phn loi nhng hng, v bn s hc cch lm trong Chng 13, " cch s dng nhng i tng DataView ."
Danh sch 11.3 trnh by mt chng trnh thc hin vic tm , lc, v sp xp nhng i tng DataRow .
Danh sch 11.3: FINDFILTERANDSORTDATAROWS.CS
/* FindFilterAndSortDataRows.cs illustrates how to find, filter, and sort DataRow objects */
using System; using System.Data; using System.Data.SqlClient;
class FindFilterAndSortDataRows { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
// set the PrimaryKey property for the Products DataTable // to the ProductID column DataTable productsDataTable = myDataSet.Tables["Products"]; productsDataTable.PrimaryKey = new DataColumn[] { productsDataTable.Columns["ProductID"] };
// set the PrimaryKey property for the Order Details DataTable // to the OrderID and ProductID columns DataTable orderDetailsDataTable = myDataSet.Tables["Order Details"]; orderDetailsDataTable.Constraints.Add( "Primary key constraint on the OrderID and ProductID columns", new DataColumn[]{orderDetailsDataTable.Columns["OrderID"], orderDetailsDataTable.Columns["ProductID"]},true); // find product with ProductID of 3 using the Find() method // to locate the DataRow using its primary key value Console.WriteLine("Using the Find() method to locate DataRow object " + "with a ProductID of 3"); DataRow productDataRow = productsDataTable.Rows.Find("3"); foreach (DataColumn myDataColumn in productsDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + productDataRow[myDataColumn]); }
// find order with OrderID of 10248 and ProductID of 11 using // the Find() method Console.WriteLine("Using the Find() method to locate DataRow object " + "with an OrderID of 10248 and a ProductID of 11"); object[] orderDetails =new object[]{10248,11}; DataRow orderDetailDataRow = orderDetailsDataTable.Rows.Find(orderDetails); foreach (DataColumn myDataColumn in orderDetailsDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + orderDetailDataRow[myDataColumn]); }
// filter and sort the DataRow objects in productsDataTable // using the Select() method Console.WriteLine("Using the Select() method to filter and sort DataRow objects"); DataRow[] productDataRows = productsDataTable.Select("ProductID <= 5", "ProductID DESC", DataViewRowState.OriginalRows); foreach (DataRow myDataRow in productDataRows) { foreach (DataColumn myDataColumn in productsDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } }
// filter and sort the DataRow objects in productsDataTable // using the Select() method Console.WriteLine("Using the Select() method to filter and sort DataRow objects"); productDataRows = productsDataTable.Select("ProductName LIKE 'Cha*'", "ProductID ASC, ProductName DESC"); foreach (DataRow myDataRow in productDataRows) { foreach (DataColumn myDataColumn in productsDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } } } The output from this program is as follows: Using the Find() method to locate DataRow object with a ProductID of 3 ProductID = 3 ProductName = Aniseed Syrup Using the Find() method to locate DataRow object with an OrderID of 10248 and a ProductID of 11 OrderID = 10248 ProductID = 11 UnitPrice = 14 Quantity = 12 Using the Select() method to filter and sort DataRow objects ProductID = 5 ProductName = Chef Anton's Gumbo Mix ProductID = 4 ProductName = Chef Anton's Cajun Seasoning ProductID = 3 ProductName = Aniseed Syrup ProductID = 2 ProductName = Chang ProductID = 1 ProductName = Chai Using the Select() method to filter and sort DataRow objects ProductID = 1 ProductName = Chai ProductID = 2 ProductName = Chang
S I NHNG HNG TRONG MT DATATABLE:
Trong mc ny, bn s thy nhng bc c yu cu thm, sa i, v loi b nhng i tng DataRow t mt DataTable v sau y nhng thay i n c s d liu. Nhng v d trong mc ny ch ra cch thm, sa i, v xa nhng hng trong bng c s d liu Customers.
Ghi nh: Bn s tm thy mt chng trnh y c tn AddModifyAndRemoveDataRows.cs trong th mc ch11, n minh ha cch s dng nhng phng thc trnh by trong mc ny. Chng trnh ny b b qua trong sch ny cho ngn gn.
THIT T MT DataAdapter Y NHNG THAY I TI C S D LIU:
Trong chng 10, bn thy trc khi bn gi phng thc Fill() ca DataAdapter ca bn c nhng hng t c s d liu, u tin bn cn thit t thuc tnh SelectCommand ca DataAdapter ca bn. Th d:
Pht biu SELECT ri c chy khi bn gi phng thc Fill() ca i tng mySqlDataAdapter truy xut nhng hng t bng Customers vo trong mt dataset.
Tng t, trc khi bn c th y nhng thay i ti c s d liu, u tin bn phi thit lp DataAdapter ca bn vi nhng i tng Command cha nhng pht biu SQL INSERT, UPDATE, v DELETE tng ng. Bn ct gi nhng i tng lnh ny trong nhng thuc tnh InsertCommand, UpdateCommand, V DeleteCommand ca i tng DataAdapter ca bn .
Bn y nhng thay i t Dataset ca bn n c s d liu s dng phng thc Update() ca DataAdapter ca bn. Khi bn thm, iu chnh, hay loi b nhng i tng DataRow t Dataset ca bn v sau gi l phng thc Update() ca DataAdapter, nhng lnh InsertCommand, UpdateCommand, hay DeleteCommand thch hp s c chy y nhng s thay i ca bn n c s d liu.
Chng ta hy xem xt cch thit t nhng thuc tnh InsertCommand, UpdateCommand, V DeleteCommand ca mt DataAdapter.
T THUC TNH INSERTCOMMAND CA MT DataAdapter:
V d sau y to ra mt i tng SqlCommand c tn myInsertCommand cha mt pht biu INSERT:
SqlCommand myInsertCommand = mySqlConnection.CreateCommand(); myInsertCommand.CommandText = "INSERT INTO Customers (" + " CustomerID, CompanyName, Address" + ") VALUES (" + " @CustomerID, @CompanyName, @Address" + ")"; myInsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); myInsertCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName"); myInsertCommand.Parameters.Add("@Address", SqlDbType.NVarChar, 60, "Address"); Bn tham s ti phng thc Add() nh sau: Tn ca tham s Kiu tham s .NET. Chiu di cc i ca chui m c th gn ti gi tr ca tham s Tn ca ct c s d liu tng ng m tham s c buc vo
Ghi nh: nhng lnh v nhng tham s c ni qua trong Chng 8, " thc thi nhng lnh C s d liu."
Nh bn c th thy trong m trc y, nhng tham s @CustomerID, @CompanyName, v @Address c buc kt ti nhng ct CustomerID, CompanyName, v Adrress trong c s d liu.
Tip theo, v d sau y gn thuc tnh InsertCommand ca mySqlDataAdapter Ti myInsertCommand:
mySqlDataAdapter.InsertCommand = myInsertCommand;
THIT T THUC TNH UpdateCommand CA MT DataAdapter:
V d sau y to ra mt i tng SqlCommand c tn myUpdateCommand c cha mt pht biu UPDATE v thit t thuc tnh UpdateCommand ca mySqlDataAdapter ti myUpdateCommand:
Mnh WHERE ca pht biu UPDATE ch r nhng tham s cho nhng ct CompanyID, CompanyName, v Address. S tranh chp lc quan nhng s dng ny, m bn s hc v n sau . Mt thuc tnh c tn SourceVersion cho nhng tham s @OldCustomerID, @OldCompanyName v @OldAddress c gn ti DataRowVersion.Original. iu ny gy ra nhng gi tr cho nhng tham s ny c thit lp ti nhng gi tr ct DataRow nguyn bn trc lc bn thay i chng.
Nhng tit mc ny xc nh s tng tranh ca UPDATE, m bn s hc ngay sau y.
S TRANH CHP:
S tng tranh qut nh nhng s thay i ca nhiu ngi s dng ti cng mt hng c x l nh th no. C hai kiu tng tranh ng dng cho mt Dataset:
S tng tranh lc quan: vi s tng tranh lc quan, bn c th sa i mt hng trong mt bng c s d liu ch khi khng ai khc cng sa i chnh hng t khi bn ti n vo trong Dataset ca bn. y in hnh l kiu tt nht ca s tng tranh s dng, bi v bn khng mun ghi ln nhng thay i ca mt ngi no .
S tng tranh " ci sau cng thng " ("Last One Wins" Concurrency) vi s tng tranh " ci sau cng thng " , bn c th lun lun sa i mt hng- v nhng s thay i ca cc bn ghi ln nhng s thay i ca bt c ai . in hnh bn lun mun trnh s dng s tng tranh " mt s chin thng cui cng " .
s dng s tng tranh lc quan, bn phi thc hin nh sau trong mnh WHERE ca pht biu UPDATE hay DELETED ca bn:.
1. Bao gm tt c nhng ct c dng trong SELECT nguyn bn. 2. Gn nhng gi tr ct ny ti nhng gi tr ban u c truy xut t hng trong bng truc lc bn thay i nhng gi tr.
Khi bn thc hin hai iu ny trong s mnh WHERE ca pht biu UPDATE hay DELEDTE ca bn , u tin pht biu kim tra xem hng nguyn bn vn cn tn ti khng trc khi cp nht hay xa hng. Cch ny, bn c th chc chn nhng s thay i ca bn khng ghi ln nhng s thay i ca bt c ai . Tt nhin, nu hng nguyn bn c xa bi ngi s dng khc, v pht biu cp nht hay xa b ca bn s tht bi.
s dng s tranh chp " ci sau cng thng " , bn phi bao gm kha chnh v gi tr ca n trong mnh WHERE ca pht biu UPDATE hay DELETE ca bn . V pht biu UPDATE ca bn khng kim tra nhng gi tr ban u, n n gin ghi ln nhng thay i ca bt c ai nu nh hng vn cn tn ti. ng thi, mt pht biu DELETE n gin xa hng cho d ngi s dng khc sa i hng .
Tr li v d m trc y, n thit t thuc tnh UpdateCommand ca mySqlDataAdapter, Bn c th thy tt c nhng ct u c bao gm trong mnh WHERE ca pht biu UPDATE . iu tha mn yu cu u tin ca vic s dng s tng tranh lc quan c ch ra trc .
Yu cu th hai l bn t ct trong mnh WHERE ti nhng gi tr hng nguyn thy. Bn lm iu ny bi thit t thuc tnh SourceVersion ca nhng tham s @OldCustomerID, @OldCompanyName, V @OldAddress ti DataRowVersion.Original. Khi thc hin, iu ny ny ko nhng gi tr nguyn thy t nhng i tng DataColumn trong DataRow trc khi bn thay i chng v t chng vo mnh WHERE ca pht biu UPDATE.
Original - chnh l mt trong nhng phn t ca lp lit k (enumeration) System.Data.DataRowVersion ; nhng ci khc c trnh by trong Bng 11.9.
Bng 11.9: nhng thnh vin Lit k DataRowVersion
Hng s M t Current Gi tr ct hin ti Default Gi tr mc nh ca ct Original Gi tr ct nguyn bn. Hng s M t Proposed Gi tr ct c xng, n c gn khi bn son tho mt DataRow s dng phng thc BeginEdit() .
THIT T THUC TNH eleteCommand CA MT DataAdapter:
V d sau y to ra mt i tng SqlCommand c tn myDeleteCommand c cha mt pht biu DELETE v thit t thuc tnh DeleteCommand ca mySqlDataAdapter ti myDeleteCommand:
Ch rng pht biu DELETE cng s dng s tng tranh lc quan.
iu ny hon thnh s ci t i tng DataAdapter.
THM MT DATAROW VO MT DATATABLE:
Trong mc ny, bn s hc cch thm mt DataRow vo mt DataTable nh th no. Trc khi bn hc iu ny, chng ta hy c tr mt Dataset vi nhng hng t bng Customers. M sau y to ra mt i tng Dataset c tn myDataSet v c tr n bi gi phng thc mySqlDataAdapter.Fill():
DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close();
Gi tr Int tr li bi phng thc Fill() l s hng c truy xut t c s d liu. i tng myDataSet by gi cha mt DataTable c tn Customers, n cha nhng hng c truy xut bi pht biu SELECT m c thit t trc trong thuc tnh SelectCommand ca mySqlDataAdapter :
SELECT CustomerID, CompanyName, Address FROM Customers ORDER BY CustomerID
thm mt hng mi vo mt i tng DataTable, bn s dng nhng bc sau y:
1. S dng phng thc NewRow() ca DataTable ca bn to ra mt DataRow mi. 2. Gn gi tr cho nhng i tng DataColumn ca DataRow mi ca bn. Ghi ch: bn c th gn mt gi tr DataColumn ti null s dng phng thc SetNull() ca mt DataRow. Bn cng c th kim tra liu mt DataColumn c cha gi tr null khng s dng phng thc IsNull() ca mt DataRow. 3. S dng phng thc Add() thng qua thuc tnh rows ca DataTable ca bn thm DataRow mi vo DataTable ca bn. 4. S dng phng thc Update() ca DataAdapter ca bn y hng mi ti c s d liu.
Phng php sau y, c tn AddDataRow(), S dng nhng bc ny thm mt hng mi vo mt DataTable:
// step 1: use the NewRow() method of the DataTable to // create a new DataRow Console.WriteLine("Calling myDataTable.NewRow()"); DataRow myNewDataRow = myDataTable.NewRow(); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState);
// step 2: set the values for the DataColumn objects of // the new DataRow myNewDataRow["CustomerID"] = "J5COM"; myNewDataRow["CompanyName"] = "J5 Company"; myNewDataRow["Address"] = "1 Main Street";
// step 3: use the Add() method through the Rows property // to add the new DataRow to the DataTable Console.WriteLine("Calling myDataTable.Rows.Add()"); myDataTable.Rows.Add(myNewDataRow); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState);
// step 4: use the Update() method to push the new // row to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState);
DisplayDataRow(myNewDataRow, myDataTable); }
Bn ch , ti gi phng thc Open() v Close() ca mySqlConnection xung quanh phng thc Update(). Bn khng cn phi lm iu ny v phng thc Update()- cng nh phng thc Fill() - s t ng m v sau ng mySqlConnection nu nh hin thi n ang ng . l thc hnh lp trnh tt, tuy nhin, r rng bao gm nhng lnh gi Open() v Close() l bn c th nhn thy chnh xc ci m chng ta ang tip tc.
Ghi ch: Trong ADO.NET kiu truy nhp d liu ngt kt ni , bn cn phi in hnh gi kt ni ti c s d liu m cng ngn cng tt. Tt nhin, nu bn ang thc hin nhiu lnh gi ti phng thc Update() hay Fill() trong mt thi gian ngn, bn c th gi cho kt ni m v sau ng n khi bn kt thc. Bng cch ny, m ca bn s thc thi tt hn . Bn c l cn th nghim nhng chng trnh ca mnh tm ra s cn bng ng.
Phng thc Update() b qu ti nh sau:
int Update(DataRow[] myDataRows) int Update(DataSet myDataSet) int Update(DataTable myDataTable) int Update(DataRow[] myDataRows, DataTableMapping myDataTableMapping) int Update(DataSet myDataSet, string dataTableName)
vi dataTableName: l mt chui cha tn ca DataTable cp nht. gi tr Int c tr li bi phng thc Update() l s lng hng c cp nht thnh cng trong c s d liu.
Quay tr li phng thc AddDataRow() trc y, bn cng nn ch s bao gm ca nhng lnh gi Connsole.WriteLine() n hin th thuc tnh RowState ca myNewDataRow. Thuc tnh RowState c gn ti mt trong s nhng hng s nh ngha trong lp lit k System.Data.DataViewRowState. Bng 11.10 cho thy rng nhng hng s nh ngha trong lp lit k DataRowState.
Bng 11.10: nhng thnh vin Lit k DataRowState
Hng s M t Added DataRow c thm vo DataRowCollection ca DataTable. Deleted DataRow c loi b t DataTable. Detached DataRow khng l phn t ca DataTable. Modified DataRow c sa i. Unchanged DataRow khng c sa i.
AddDataRow() Gi mt phng thc c tn DisplayDataRow(), n hin th nhng gi tr DataColumn cho DataRow c gi qua nh tham s u tin. DisplayDataRow() c nh ngha nh sau:
Trong phng thc AddDataRow() trc y, bn thy rng n trnh by nhiu im ca thuc tnh RowState ca myNewDataRow . u ra t AddDataRow() v nhng lnh gi ti DisplayDataRow() nh sau:
In AddDataRow() Calling myDataTable.NewRow() myNewDataRow.RowState = Detached Calling myDataTable.Rows.Add() myNewDataRow.RowState = Added Calling mySqlDataAdapter.Update() numOfRows = 1 myNewDataRow.RowState = Unchanged In DisplayDataRow() CustomerID = J5COM CompanyName = J5 Company Address = 1 Main Street
Chng ta hy kho st chi tit qu trnh chy m ny :
Sau khi myDataTable.NewRow() c gi to ra myNewDataRow, RowState ca n l Detached (tch ra), n ch nh myNewDataRow khng cn l phn t ca myDataTable. Tip theo, myDataTable.Row.Add() c gi thm myNewDataRow vo myDataTable. iu ny gy ra RowState ca myNewDataRow thay i v Added, n cho bit myNewDataRow by gi l phn t ca myDataTable. Cui cng, mySqlDataAdapter.Update() c gi y hng mi ti c s d liu. iu ny gy ra RowState ca myNewDataRow thay i ti Unchanged.
ng sau ng cnh, phng thc Update() chy pht biu INSERT trong thuc tnh mySqlDataAdapter. InsertCommand thm hng mi ti bng Customers. gi tr Int c tr li bi pht biu Update() l s lng hng b nh hng bi vic gi phng thc. Trong v d ny, 1 c tr v v mt hng c thm vo.
SA I MT DATAROW TRONG MT DATATABLE:
sa i mt DataRow trong mt DataTable, Bn theo nhng bc sau y
1. Thit t thuc tnh PrimaryKey ca DataTable ca cc bn. Bn cn thit t n tm kim DataRow trong bc tip theo. 2. S dng phng thc Find() nh v DataRow m bn mun sa i trong DataTable ca bn. Bn nh v DataRow s dng gi tr ct kha chnh ca n. 3. Thay i nhng gi tr DataColumn cho DataRow ca bn. 4. S dng phng thc Update() ca i tng DataAdapter ca bn y hng c sa i ti c s d liu.
Phng thc sau y, c tn ModifyDataRow(), S dng nhng bc ny sa i hng c thm vo trc bi phng thc AddDataRow() :
// step 1: set the PrimaryKey property of the DataTable myDataTable.PrimaryKey = new DataColumn[]{myDataTable.Columns["CustomerID"]};
// step 2: use the Find() method to locate the DataRow // in the DataTable using the primary key value DataRow myEditDataRow = myDataTable.Rows.Find("J5COM");
// step 4: use the Update() method to push the modified // row to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myEditDataRow.RowState = " + myEditDataRow.RowState);
DisplayDataRow(myEditDataRow, myDataTable); }
t kha chnh trong bc 1 khng phi c thc hin trong phng thc ModifyDataRow() . Bn c th, chng hn, t kha chnh ngay sau khi gi phng thc Fill() trong phng thc Main() ca chng trnh AddModifyAndRemoveDataRows.cs . L do Ti t kha chnh trong ModifyDataRow() l bn c th cng nhn thy tt c nhng bc trong phng thc ny.
Ch trong bc 3 ca phng thc ny gi tr nguyn thy ca i tng DataColumn : CustomerID, CompanyName, V Address c trnh by s dng hng s DataRowVersion. Original . y l nhng gi tr nguyn thy ca DataColumn trc khi chng c thay i. Nhng gi tr hin ti ca nhng i tng DataColumn : CompanyName v Address cng c hin th s dng hng s DataRowVersion.Current . y l nhng gi tr DataColumn sau khi chng c thay i.
u ra t ModifyDataRow() v nhng lnh gi ti DisplayDataRow() nh sau:
In ModifyDataRow() myEditDataRow.RowState = Modified myEditDataRow["CustomerID", DataRowVersion.Original] = J5COM myEditDataRow["CompanyName", DataRowVersion.Original] = J5 Company myEditDataRow["Address", DataRowVersion.Original] = 1 Main Street myEditDataRow["CompanyName", DataRowVersion.Current] = Widgets Inc. myEditDataRow["Address", DataRowVersion.Current] = 1 Any Street Calling mySqlDataAdapter.Update() numOfRows = 1 myEditDataRow.RowState = Unchanged
In DisplayDataRow() CustomerID = J5COM CompanyName = Widgets Inc. Address = 1 Any Street
Ch : i tng DataColumn -CompanyName v Address ca myEditDataRow c thay i. thuc tnh RowState ca myEditDataRow thay i ti Modified sau khi CompanyName v Address ca n c thay i, v sau ti Unchanged mySqlDataAdapter.Updatwe() c gi .
NH DU NHNG S SA I CA BN:
Bn c th s dng phng thc BeginEdit() nh du s bt u ca mt s sa i ti mt DataRow. Chng hn:
myEditDataRow.BeginEdit(); myEditDataRow["CompanyName"] = "Widgets Inc."; myEditDataRow["Address"] = "1 Any Street";
Ri bn s dng c hai phng thc EndEdit() hay CancelEdit() nh du kt thc s sa i ti DataRow. EndEdit() giao ph s sa i; CancelEdit() loi b s sa i v khi phc DataRow ti pht biu nguyen bn ca n trc tr luc son tho bt u.
V d sau y gi phng thc EndEdit() ca myEditDataRow giao ph nhng thay i a thc hin trong v d trc.
myEditDataRow.EndEdit();
XA MT DATAROW T MT DATATABLE:
loi b mt DataRow t mt DataTable, bn s dng nhng bc sau y:
1. t thuc tnh PrimaryKey cho i tng DataTable ca bn. 2. S dng phng thc Find() nh v DataRow ca bn. 3. S S dng phng thc Delete() loi b DataRow ca bn. 4. S dng phng thc Update() y lnh xoa ti c s d liu.
Phng thc sau y, c tn RemoveDataRow(), s dng nhng bc ny loi b DataRow m trc c sa i bi phng thc ModifyDataRow() :
// step 1: set the PrimaryKey property of the DataTable myDataTable.PrimaryKey = new DataColumn[]{myDataTable.Columns["CustomerID"]};
// step 2: use the Find() method to locate the DataRow DataRow myRemoveDataRow = myDataTable.Rows.Find("J5COM");
// step 3: use the Delete() method to remove the DataRow Console.WriteLine("Calling myRemoveDataRow.Delete()"); myRemoveDataRow.Delete(); Console.WriteLine("myRemoveDataRow.RowState = " + myRemoveDataRow.RowState);
// step 4: use the Update() method to remove the deleted // row from the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myRemoveDataRow.RowState = " + myRemoveDataRow.RowState); }
Ch : Thuc tnh RowState ca myRemoveDataRow c t ti Deleted sau khi myRemoveData.Delete() c gi, v sau ti Detachedsau khi mySqlDataAdapter.Update() c gi - c ngha l myRemoveDataRow khng cn l phn t ca DataTable.
Ghi nh : Bn s tm thy mt chng trnh y c tn AddModifyAndRemoveDataRows.cs trong th mc ch11 n minh ha cch s dng ca nhng phng thc AddDataRow(), ModifyDataRow(), v RemoveDataRow() . Danh sch chng trnh ny c b qua trong sch ny cho ngn gn.
TRUY XUT NHNG GI TR CT NHN DNG (KHA CHNH):
Ct ProductID ca bng Products l mt ct "cn cc"(ct kha chnh). Trong mc ny bn s thy cch chn mt hng mi vo bng Products v truy xut gi tr mi c pht sinh bi c s d liu cho ct kha chnh ProductID nh th no.
Ghi nh: Bn s tm thy mt chng trnh y c tn UsingIdentityColumn.cs trong th mc ch11 n minh ha s s dng ca nhng phng thc trnh by trong mc ny. Danh sch chng trnh ny c b qua trong sch ny cho ngn gn.
Trong nhng v d, gi thit bn c mt DataTable c tn productsDataTable m c lu tr vi nhng hng c truy xut bi pht biu SELECT sau y.
SELECT ProductID, ProductName, UnitPrice FROM Products ORDER BY ProductID
V d sau y thit t thuc tnh PrimaryKey ca productsDataTable:
productsDataTable.PrimaryKey = new DataColumn[] { productsDataTable.Columns["ProductID"] };
Nhng v d k tip thit t thuc tnh AutoIncrement, AutoIncrementSeed, AutoIncrementStep, ReadOnly, v Unique cho DataColumn ProductID ca productsDataTable:
V nhng s thit t ny, khi bn thm mt DataRow mi vo productsDataTable, ProductID DataColumn ca DataRow mi ca bn thot tin s c gi tr -1.
Nh trong mc trc , " Sa i nhng hng trong mt DataTable, " Bn cn t thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca i tng DataAdapter ca bn nhng i tng lnh thch hp. Thuc tnh CommandText ca i tng Command c dng trong thuc tnh UpdateCommand nh sau:
Ch : CommandText ca hai i tng Command ny khng khc bit ng k vi nhng g c trnh by trong mc trc , ch c iu n i ngc li bng Products hn l bng Customers.
S khc nhau thc s l trong CommandText ca i tng Command s dng trong thuc tnh InsertCommand - phi truy xut gi tr ProductID pht sinh bi c s d liu cho hng mi. thc hin iu ny, bn c th s dng m sau y c cha mt pht biu INSERT thm mt hng mi, cng vi mt pht biu SELECT truy xut gi tr ProductID s dng mt lnh gi ti hm SQL Server:SCOPE_IDENTITY() :
SCOPE_IDENTITY() hm tr li gi tr nhn dng(kha chnh) c thm sau cng vo trong bt k bng no c thc hin bn trong phin c s d liu hin thi v store prosedure, trig, function, hay batch. Chng hn, vic gi SCOPE_IDENTITY() trong v d trc tr li gi tr nhn dng(kha chnh) c thm sau cng vo trong bng Products, chnh l ProductID ca hng mi
Ghi ch: cho nhng chi tit v hm SCOPE_IDENTITY() , tham chiu ti Chng 4, " gii thiu v lp trnh Transact-SQL ."
Khi bn thm mt DataRow mi vo productsDataTable, DataColumn ProductID ca DataRow mi ca bn thot tin s c gi tr -1. Khi bn gi phng thc Update() ca SqlDataAdapter ca bn y hng mi ti c s d liu, nhng bc sau y s xut hin:
1. DataRow mi ca bn c y ti c s d liu s dng pht biu INSERT c thit t trong myInsertCommand, vi ct ProductID ca bng Products ang c gn ti mt gi tr "cn cc" mi pht sinh bi c s d liu. 2. Gi tr cn cc ProductID c truy xut bi pht biu SELECT gn trong myInsertCommand. 3. Ct d liu ProductId trong DataRow ca bn c gn ti gi tr "cn cc" c truy xut.
C t nhin kho st, bin tp, v chy chng trnh UsingIdentityColumn.cs c lu tr trong th mc ch11. Chng trnh ny thc hin nhng hot ng cp cao sau y:
1. Truy xut nhng hng t bng Products vo trong mt DataTable c tn productsDataTable. 2. Thm mt DataRow vo productsDataTable. 3. Sa i DataRow mi. 4. Xa DataRow mi.
Khi bn chy chng trnh ny bn s ch s thay i ca gi tr ct d liu ProductID cho mt DataRow mi thm vo t -1 n mt gi tr thc truy xut t c s d liu.
S DNG NHNG TH TC PROCEDURE THM, SA, XA NHNG HNG T C S D LIU
Bn c th dng mt i tng DataAdapter gi nhng th tc lu tr thm, sa i, v loi b nhng hng t c s d liu. Nhng th tc ny c gi thay cho nhng pht biu INSERT, UPDATE, v DELETE m bn c thy cch thit t cc thuc tnh InsertCommand, UpdateCommand, v DeleteCommand cho mt i tng DataAdapter .
Kh nng gi nhng th tc lu tr s dng mt DataAdapter l mt b sung rt mnh ti ADO.NET. v d bn c th s dng mt th tc lu tr thm mt hng vo mt bng c cha mt ct kha chnh, v truy xut gi tr mi cho ct ny c pht sinh bi c s d liu. Bn cng c th thc hin vic b sung trong mt th tc lu tr nh chn mt hng vo trong mt bng kim ton khi mt hng c sa i. Bn s thy nhng v d ca c hai kch bn ny trong mc ny.
Mo nh : s dng nhng th tc lu tr thay v nhng pht biu Chn, s Cp nht, v Xa c th cng ci thin s thc thi. Bn cn phi s dng nhng th tc lu tr nu c s d liu ca bn h tr chng. SQL Server v Oracle h tr nhng th tc lu tr. nhng th tc lu tr Oracle c vit trong PL/ SQL.
Ct ProductID ca bng Products l mt ct kha chnh, v bn thy mt s th tc lu tr trong Chng 4, " gii thiu v lp trnh giao dch- SQL " m thm mt hng vo nhng bng sn phm v tr li ProductID.
Trong mc ny, bn s thy cch
To ra nhng th tc lu tr c yu cu trong c s d liu Northwind. thit lp mt DataAdapter gi nhng th tc lu tr. Thm, sa i, v loi b mt DataRow t mt DataTable.
Nhng phng thc C# c trnh by trong mc ny i theo nhng bc tng t nh trnh by trong mc trc , " Sa i nhng hng mt DataTable."
Ghi nh: Bn s tm thy mt chng trnh y c tn PushChangesUsingProcedures.cs trong th mc ch11 minh ha s s dng ca nhng phng thc trnh by trong mc ny. Danh sch cho chng trnh ny c b qua trong sch ny cho ngn gn.
TO STORED PROCEDURES TRONG C S D LIU:
Bn s to ra ba th tc lu tr trong c s d liu Northwind nhu sau:
AddProduct4(), m thm mt hng vo nhng bng sn phm. UpdateProduct(), n cp nht mt hng trong bng Products. DeleteProduct(), xa mt hng t nhng bng sn phm.
Chng ta hy xem xt nhng th tc ny.
TH TC LU TR AddProduct4()
AddProduct4() thm mt hng vo bng Products. N s dng s 4 v nhng chng trc s dng nhng th tc c tn AddProduct(), AddProduct2(), V AddProduct3().
Danh sch 11.4 trnh by file AddProduct4.sql m bn s dng to ra th tc AddProduct4() . Hy tham chiu ti Chng 4 nu bn cn mt nc gii kht trn Ngn ng Giao dch- SQL (Transact-SQL language) hay nu bn cn tm hiu cch chy script ny to ra th tc trong c s d liu.
Danh sch 11.4: ADDPRODUCT4. SQL /* AddProduct4.sql creates a procedure that adds a row to the Products table using values passed as parameters to the procedure. The procedure returns the ProductID of the new row using a RETURN statement */
CREATE PROCEDURE AddProduct4 @MyProductName nvarchar(40), @MyUnitPrice money AS
-- declare the @MyProductID variable DECLARE @MyProductID int
-- insert a row into the Products table INSERT INTO Products ( ProductName, UnitPrice ) VALUES ( @MyProductName, @MyUnitPrice )
-- use the SCOPE_IDENTITY() function to get the last -- identity value inserted into a table performed within -- the current database session and stored procedure, -- so SCOPE_IDENTITY returns the ProductID for the new row -- in the Products table in this case SET @MyProductID = SCOPE_IDENTITY()
RETURN @MyProductID
Ghi ch: Bn s tm thy AddProduct4.sql trong th mc ch11.
TH TC UpdateProduct()
/* UpdateProduct.sql creates a procedure that modifies a row in the Products table using values passed as parameters to the procedure */
-- update the row in the Products table UPDATE Products SET ProductName = @NewProductName, UnitPrice = @NewUnitPrice WHERE ProductID = @OldProductID AND ProductName = @OldProductName AND UnitPrice = @OldUnitPrice
V mnh WHERE cha nhng gi tr ct c trong pht biu Update ca th tc ny, UPDATE s dng s tng tranh lc quan c m t trc . c ngha l mt ngi s dng khng ghi ln nhng thay i ca ngi s dng khc.
TH TC DeletProduct()
DeleteProduct() xa mt hng t bng Products. Danh sch 11.6 trnh by tp tin DeleteProduct.sql m bn s dng to ra th tc DeleteProduct() .
Danh sch 11.6: DELETEPRODUCT.SQL
/* DeleteProduct.sql creates a procedure that removes a row from the Products table */
CREATE PROCEDURE DeleteProduct @OldProductID int, @OldProductName nvarchar(40), @OldUnitPrice money AS
-- delete the row from the Products table DELETE FROM Products WHERE ProductID = @OldProductID AND ProductName = @OldProductName AND UnitPrice = @OldUnitPrice
S DNG SET NOCOUNT ON TRONG STORED PROCEDURES
Trong Chng 4, " gii thiu v Lp trnh Giao dch- SQL " bn thy bn s dng command NET NOCOUNT ON ngn nga Transact- SQL v vic tr li s lng hng b nh hng. in hnh, bn phi trnh s dng lnh ny trong th tc lu tr ca bn bi v DataAdapter s dng s lng hng c nh hng c tr li bit liu c phi s cp nht thnh cng.
C mt tnh hung khi bn phi s dng SET NOCOUNT ON : Khi th tc lu tr ca bn thc hin mt pht biu Chn, s Cp nht hay Xa s m nh hng n bng khc khng k mt chnh bn ang y mt s thay i Ti. Chng hn, ni DeleteProduct() Th tc cng thc hin mt s pht biu Chn thm mt hng vo bng ProductAudit (c m t trong Chng 4) ghi s n lc xa hng t nhng bng sn phm. Trong v d ny, bn phi s dng Tp hp NOCOUNT Trn vic trc y thc hin s Chn vo trong bng ProductAudit, nh c a vo lit k 11.7.
Danh sch 11.7: DELETEPRODUCT2. SQL
/* DeleteProduct2.sql creates a procedure that removes a row from the Products table */
CREATE PROCEDURE DeleteProduct2 @OldProductID int, @OldProductName nvarchar(40), @OldUnitPrice money AS -- delete the row from the Products table DELETE FROM Products WHERE ProductID = @OldProductID AND ProductName = @OldProductName AND UnitPrice = @OldUnitPrice
-- use SET NOCOUNT ON to suppress the return of the -- number of rows affected by the INSERT statement SET NOCOUNT ON
-- add a row to the Audit table IF @@ROWCOUNT = 1 INSERT INTO ProductAudit ( Action ) VALUES ( 'Product deleted with ProductID of ' + CONVERT(nvarchar, @OldProductID) ) ELSE INSERT INTO ProductAudit ( Action ) VALUES ( 'Product with ProductID of ' + CONVERT(nvarchar, @OldProductID) + ' was not deleted' )
Do vic s dng SET NOCOUNT ON trc lnh INSERT, ch c s lng hng nh hng bi pht biu DELETE c tr v, v do DataAdapter ly c gi tr ng.
Transact- SQL cng c mt Command SET NOCOUNT ON tr v s lng hng b nh hng. Bn c th s dng mt s kt hp ca SET NOCOUNT OFF v SET NOCOUNT ON nu nh Bn cn thc hin mt pht biu Chn, Cp nht, hay Xa trc pht biu SQL chnh trong th tc lu tr ca cc bn.
THIT LP MT DataAdapter GI NHNG TH TC LU TR:
Nh c cp trong mc trc - " Sa i nhng hng trong mt DataTable, " Bn cn to ra mt i tng DataAdapter v gn nhng thuc tnh SelectCommand, InsertCommand, UpdateCommand, v DeleteCommand ca n vi nhng i tng Command thch hp . Tuy nhin, lc ny, nhng thuc tnh InsertCommand, UpdateCommand, v DeleteCommand s cha nhng i tng Command gi nhng th tc lu tr c c trnh by trc .
u tin, v d sau y to ra mt i tng SqlCommand cha mt pht biu SELECT v thit t nhng thuc tnh SelectCommand ca mt SqlDataAdapter ti SqlCommand ny:
Pht biu SELECT c chy khi bn gi phng thc Fill() ca i tng mySqlDataAdapter truy xut nhng hng t bng Product vo trong mt Dataset.
Trc khi bn c th y nhng thay i ti c s d liu, bn phi gn nhng thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca DataAdapter ca bn vi nhng i tng Command. Nhng i tng Command ny s cha nhng lnh gi ti nhng th tc lu tr AddProduct4(), UpdateProduct(), V DeleteProduct() m bn to ra trc . Ri bn thm, iu chnh, hay loi b nhng i tng DataRow t Dataset ca bn, v sau gi phng thc Update() ca DataAdapter ca bn , Th tc lu tr thch hp c chy y nhng s thay i ca bn ti c s d liu.
Chng ta hy xem xt cch thit t nhng thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca DataAdapter ca bn.
THIT T THUC TNH InsertCommand CA DataAdapter:
V d sau y to ra mt i tng SqlCommand c tn myInsertCommand cha mt lnh gi ti th tc lu tr AddProduct4() :
Nh bn c th thy t m trc y, hng ca tham s @MyProductID c gn l ParameterDirection.Output , n ch nh tham s ny l mt tham s u ra. ng thi, chiu di cc i ca nhng tham s @MyProductID v @MyUnitPrice c gn l 0 trong tham s th ba ca phng thc Add(). Vic gn chng ti 0 s tt hn bi v chiu di cc i khng ng dng vi nhng kiu di c nh nh nhng con s, m ch ng dng vi nhng kiu nh nhng chui.
Tip theo, v d sau y t thuc tnh InsertCommand ca mySqlDataAdapter Ti myInsertCommand:
mySqlDataAdapter.InsertCommand = myInsertCommand;
THIT T THUC TNH UpdateCommand CA MT DataAdapter:
V d sau y to ra mt i tng SqlCommand c tn myUpdateCommand cha mt lnh gi ti th tc lu tr UpdateProduct() v gn thuc tnh UpdateCommand ca mySqlDataAdapter l myUpdateCommand:
V d sau y to ra mt i tng SqlCommand c tn myDeleteCommand cha mt lnh gi ti th tc lu tr DeleteProduct() v gn thuc tnh DeleteCommand ca mySqlDataAdapter l myDeleteCommand:
Trong mc ny, bn s hc cch thm mt DataRow vo mt DataTable . u tin, m sau y to ra mt i tng Dataset c tn myDataSet v c tr n bi vic gi mySqlDataAdapter. Fill():
DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); mySqlConnection.Close();
Gi tr Int tr v bi phng thc Fill() l s lng hng c truy xut t c s d liu v sao chp ti myDataSet. i tng myDataSet by gi cha mt DataTable c tn Products, n cha nhng hng c truy xut bi pht biu SELECT thit lp trc trong thuc tnh SelectCommand ca mySqlDataAdapter :
SELECT ProductID, ProductName, UnitPrice FROM Products ORDER BY ProductID
thm mt hng mi vo mt i tng DataTable , bn s dng bn bc tng t nh trnh by trc trong mc " sa i mt DataRow mt DataTable." Phng thc sau y, c tn AddDataRow(), s dng nhng bc ny thm mt hng mi vo mt DataTable:
public static int AddDataRow( DataTable myDataTable, SqlDataAdapter mySqlDataAdapter, SqlConnection mySqlConnection ) { Console.WriteLine("\nIn AddDataRow()");
// step 1: use the NewRow() method of the DataTable to // create a new DataRow Console.WriteLine("Calling myDataTable.NewRow()"); DataRow myNewDataRow = myDataTable.NewRow(); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState);
// step 2: set the values for the DataColumn objects of // the new DataRow myNewDataRow["ProductName"] = "Widget"; myNewDataRow["UnitPrice"] = 10.99;
// step 3: use the Add() method through the Rows property // to add the new DataRow to the DataTable Console.WriteLine("Calling myDataTable.Rows.Add()"); myDataTable.Rows.Add(myNewDataRow); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState); // step 4: use the Update() method to push the new // row to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myNewDataRow.RowState = " + myNewDataRow.RowState);
DisplayDataRow(myNewDataRow, myDataTable);
// return the ProductID of the new DataRow return (int) myNewDataRow["ProductID"]; }
Ch khng c gi tr no cho ct d liu ProductID c thit t trong bc 2. Bi v ProductID t ng c pht sinh bi c s d liu khi hng mi c y ti c s d liu bi phng thc Update() trong bc 4.
Khi phng thc Update() c gi , th tc lu tr AddProduct4() c chy thm hng mi vo bng Products. Ri c s d liu pht sinh mt ProductID mi cho hng, gi tr ny c tr v bi th tc lu tr AddProduct4() . V bn c th c ProductID mi bi s dng myNewDataRow[" ProductID "], m by gi cha ProductID mi. ProductID ny c tr v vo thi im cui cng ca thc thi phng thc AddDataRow().
u ra t AddDataRow() v lnh gi ca n ti DisplayDataRow() nh sau:
Nh bn c th thy, sau khi myDataTable.NewRow() c gi to ra myNewDataRow, RowState ca n l Detached, cho bit myNewDataRow khng cn l phn t ca myDataTable.
Tip theo, myDataTable.Row.Add() c gi thm myNewDataRow vo myDataTable. iu ny gy ra RowState ca myDataTable thay i thnh Added, cho bit myNewDataRow c thm vo myDataTable. Cui cng, mySqlDataAdapter.Update() c gi y hng mi ti c s d liu.Th tc lu tr AddProduct4() c chy thm hng mi vo bng Products , v RowState ca myNewDataRow thay i thnh Unchanged.
THAY I MT DataRow TRONG MT DataTable:
Phng thc sau y, c tn ModifyDataRow(), s dng bn bc sa i mt DataRow trong mt i tng DataTable. Ch rng ProductID chnh sa c gi qua nh mt tham s.
public static void ModifyDataRow( DataTable myDataTable, int productID, SqlDataAdapter mySqlDataAdapter, SqlConnection mySqlConnection ) { Console.WriteLine("\nIn ModifyDataRow()");
// step 1: set the PrimaryKey property of the DataTable myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns["ProductID"] };
// step 2: use the Find() method to locate the DataRow // in the DataTable using the primary key value DataRow myEditDataRow = myDataTable.Rows.Find(productID);
// step 4: use the Update() method to push the update // to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myEditDataRow.RowState = " + myEditDataRow.RowState);
DisplayDataRow(myEditDataRow, myDataTable); }
Ch phng thc ny trnh by nhng gi tr ban u ca nhng i tng DataColumn : ProductID, ProductName, v UnitPrice s dng DataRowVersion.Original.Constant . y l nhng gi tr DataColumn trc khi chng c thay i. Phng thc cng trnh by nhng gi tr hin ti cho nhng i tng ct d liu ProductName v UnitPrice s dng hng s DataRowVersion.Current . y l nhng gi tr DataColumn sau khi chng c thay i. Khi phng thc Update() c gi trong bc 4, th tc lu tr UpdateProduct() c chy pha sau ng cnh thc hin s cp nht.
u ra t ModifyDataRow() v lnh gi ca ti DisplayDataRow() nh sau:
Ch rng thuc tnh RowState ca myEditDataRow thay i thnh Modified sau khi d liu ca n c thay i, v ri thnh Unchange sau khi mySqlDataAdapter.Update() c gi .
XA B MT DataRow T MT DataTable:
Phng thc sau y, c tn RemoveDataRow(), s dng bn bc loi b mt DataRow t mt DataTable. Ch ProductID iu chnh c gi qua nh mt tham s.
public static void RemoveDataRow( DataTable myDataTable, int productID, SqlDataAdapter mySqlDataAdapter, SqlConnection mySqlConnection ) { Console.WriteLine("\nIn RemoveDataRow()");
// step 1: set the PrimaryKey property of the DataTable myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns["ProductID"] };
// step 2: use the Find() method to locate the DataRow DataRow myRemoveDataRow = myDataTable.Rows.Find(productID);
// step 3: use the Delete() method to remove the DataRow Console.WriteLine("Calling myRemoveDataRow.Delete()"); myRemoveDataRow.Delete(); Console.WriteLine("myRemoveDataRow.RowState = " + myRemoveDataRow.RowState);
// step 4: use the Update() method to push the delete // to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myRemoveDataRow.RowState = " + myRemoveDataRow.RowState); } u ra t RemoveDataRow() nh sau: In RemoveDataRow() Calling myRemoveDataRow.Delete() myRemoveDataRow.RowState = Deleted Calling mySqlDataAdapter.Update() numOfRows = 1 myRemoveDataRow.RowState = Detached
Ch rng thuc tnh RowState ca myRemoveDataRow c gn l Deleted sau khi myRemoveData.Delete() c gi, v chuyn thnh Detached sau khi mySqlDataAdapter.Update() c gi. Khi phng thc Update() c gi trong bc 4, Th tc lu tr DeleteProduct() c chy ng sau ng cnh thc hin vc xa.
Ghi nh Bn s tm thy mt chng trnh y c tn PushChangesUsingProcedures.cs trong th mc ch11 minh ha s s dng ca nhng phng thc AddDataRow(), ModifyDataRow(), V RemoveDataRow(). Danh sch ny c b qua trong sch ny cho ngn gn.
T NG PHT SINH NHNG PHT BIU SQL:
Nh bn thy trong nhng mc trc y, vic cung cp nhng pht biu INSERT, UPDATE, v DELETE hay nhng th tc lu tr ca bn y nhng s thay i t Dataset ca bn n c s d liu c ngha bn phi b cng vit nhiu m. Bn c th trnh vit m ny bi vic s dng mt i tng CommandBuilder, m c th t ng pht sinh nhng lnh (Command) INSERT, UPDATE, v DELETE bng n l , m y nhng s thay i bn thc hin vi mt i tng Dataset n c s d liu. Ri nhng lnh ny c gn vo nhng thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca i tng DataAdapter ca bn .
Mc d bn c tit kim thi gia ghi mt vi dng m nh s dng CommandBuilder, Bn phi nh nhng gii hn sau y khi s dng mt CommandBuilder:
Thuc tnh SelectCommand ca DataAdapter ca bn ch c th truy xut nhng hng t mt bng n. Bng c s d liu c dng trong SelectCommand ca bn phi cha ng mt kha chnh. Kha chnh ca bng phi c bao gm trong SelectCommand ca cc bn. CommandBuilder mt mt s lng nht nh thi gian pht sinh nhng lnh bi v n phi kho st c s d liu .
Cnh bo: Bi v mt CommandBuilder lm chm s thc thi ca chng trnh ca bn, bn cn phi trnh s dng chng. chng c d nh cho s s dng bi nhng ngi pht trin m khng quen thuc vi SQL hay th tc lu tr. thc hin tt nht, bn s dng nhng th tc lu tr.
C ba lp nh cung cp c qun l CommandBuilder : SqlCommandBuilder, OleDbCommandBuilder, v OdbcCommandBuilder. Bn s thy s s dng mt i tng SqlCommandBuilder trong mc ny, n lm vic vi mt c s d liu ngi phc v SQL .Nhng kiu i tng khc lm vic trong cng mt cch .
u tin, bn cn thit t thuc tnh SelectCommand ca mt i tng SqlDataAdapter. Pht biu SELECT c dng trong lnh (Command) ny ch c th truy xut nhng hng t mt bng n, v trong v d sau y bng Customers c s dng
Tip theo, v d sau y to ra mt i tng SqlCommandBuilder, thng qua mySqlDataAdapter n B khi to.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
SqlCommandBuilder s pht sinh nhng lnh (Command) cha pht biu Chn, Cp nht, v Xa da vo pht biu SELECT trc c gn trong thuc tnh SelectCommand ca i tng mySqlDataAdapter.
Bn c th thu c c nhng lnh pht sinh - s dng nhng phng thc GetInsertCommand(), GetUpdateCommand(), v GetDeleteCommand() ca mySqlCommandBuilder. Chng hn:
M ny hin th u ra sau y ( Ti c thm vi khong trng lm cho m d c hn)
mySqlCommandBuilder.GetInsertCommand().CommandText = INSERT INTO Customers(CustomerID , CompanyName , Address) VALUES (@p1 , @p2 , @p3) mySqlCommandBuilder.GetUpdateCommand().CommandText = UPDATE Customers SET CustomerID = @p1 , CompanyName = @p2 , Address = @p3 WHERE (CustomerID = @p4 AND CompanyName = @p5 AND Address = @p6) mySqlCommandBuilder.GetDeleteCommand().CommandText = DELETE FROM Customers WHERE (CustomerID = @p1 AND CompanyName = @p2 AND Address = @p3)
Nh bn c th thy, nhng lnh ny tng t nh nhng lnh trnh by trc trong mc " Sa i nhng hng mt DataTable." Nhng cu lnh SQL c dng trong nhng lnh ny s dng s tng tranh lc quan.
By gi bn c th c tr v thc hin nhng thay i ti mt DataTable cha nhng hng t bng Customers, ri y nhng thay i ti c s d liu s dng phng thc Update(). Bn c th s dng phng thc AddDataRow(), ModifyDataRow(), V RemoveDataRow() nh trnh by trong mc trc , " Sa i nhng hng mt DataTable."
Ghi nh : Bn s tm thy mt chng trnh y c tn UsingCommandBuilder.cs trong th mc ch11 minh ha s s dng i tng CommandBuilder trnh by trong mc ny. Danh sch ny c b qua trong sch ny cho ngn gn.
KHM PH DataAdapter V NHNG S KIN DataTable:
Bn s tm thy tt c nhng m v d c c trnh by trong mc ny trong chng trnh UsingEvents.cs trong th mc ch11. Danh sch chng trnh ny c b qua trong sch ny cho ngn gn. Nu bn bin dch v chy chng trnh ny, bn s thy trnh t m trong nhng s c pht khi khi bn thm, sa i, v loi b mt hng t mt DataTable c cha nhng hng c truy xut t bng Customers.
NHNG S KIN DataAdapter:
Nhng s c c pht khi bi mt i tng SqlDataAdapter c trnh by trong Bng 11.11.
Bng 11.11: nhng s kin SqlDataAdapter S KIN EVENT HANDLER M T FillError FillErrorEventHandler Pht khi khi mt li xut hin trong thi gian mt lnh gi ti phng thc Fill() . RowUpdating RowUpdatingEventHandler Pht khi trc khi mt hng c b sung, iu chnh, hay xa trong c s d liu nh mt kt qu ca vic gi phng thc Update() . RowUpdated RowUpdatedEventHandler Pht khi sau khi mt hng c b sung, iu chnh, hay xa trong c s d liu nh mt kt qu ca vic gi phng php Update() .
S KIN FillError:
S kin FillError pht khi khi bn gi phng thc Fill() m mt li xy ra. Sau y l mt cp tnh hung s gy ra mt li :
Mt n lc thm mt s t c s d liu n mt DataColumn m vn khng th chuyn i c vo kiu d liu .NET ca DataColumn ny m khng mt s chnh xc. Mt n lc thm mt hng t c s d liu n mt DataTable m xm phm mt s rng buc trong DataTable ny.
v d v B x l s kin (event handler) sau y, c tn FillErrorEventHandler(), kim tra li chuyn i chnh xc:
public static void FillErrorEventHandler( object sender, FillErrorEventArgs myFEEA ) { if (myFEEA.Errors.GetType() == typeof(System.OverflowException)) { Console.WriteLine("A loss of precision occurred"); myFEEA.Continue = true; } }
Tham s u tin l mt i tng ca lp System.Object , v n i din cho i tng pht khi s kin. Tham s th hai l mt i tng ca lp FillErrorEventArgs, n ging nh tt c nhng lp EventArgs, c dn xut t lp System.EventArgs. Lp EventArgs l lp c s cho d liu s kin v i din cho nhng chi tit ca s kin. Bng 11.12 cho thy nhng thuc tnh FillErrorEventArgs.
Bng 11.12: nhng thuc tnh FillErrorEventArgs Thuc tnh Kiu M t Continue bool Ly hay gn mt gi tr bool cho bit liu c phi bn mun tip tc in y Dataset ca bn mc d c mt li xy ra. mc nh l false. DataTable DataTable Ly DataTable m c in y khi li xut hin. Errors Exception Ly ngoi l ang cha li sy ra. Values object[] Ly nhng gi tr DataColumn ca DataRow m trong li xy ra. Nhng gi tr ny c tr li trong mt mng i tng.
Bn ch nh mySqlDataAdapter s gi phng thc FillErrorEventHandler() khi s kin FillError khi pht s dng m sau y:
mySqlDataAdapter.FillError += new FillErrorEventHandler(FillErrorEventHandler);
S KHIN RowUpdating:
S kin RowUpdating pht khi trc khi mt hng c cp nht trong c s d liu nh mt kt qu ca phng thc Update() ca DataAdapter ca bn m bn gi. S kin ny pht khi mt ln cho mi DataRow bn b sung, sa i, hay xa mt DataTable.
Nhng hot ng sau y c thc hin pha sau ng cnh cho mi DataRow khi bn gi phng thc Update() ca DataAdapter ca bn :
1. Nhng gi tr trong DataRow ca cc bn c sao chp ti nhng gi tr tham s ca lnh(Command) thch hp trong thuc tnh InsertCommand, UpdateCommand, hay DeleteCommand ca DataAdapter ca bn.
2. S kin RowUpdating ca DataAdapter ca cc bn khi pht . 3. Lnh ( Command) c chy y s thay i ti c s d liu. 4. Mi tham s u ra t Command c tr v. 5. S kin RowUpdated ca DataAdapter ca bn khi pht . 6. Phng thc AcceptChanges() ca DataRow ca bn c gi .
Tham s th hai ti bt k phng thc b x l s kin no bn vit x l s kin RowUpdating ca mt i tng SqlDataAdapter u thuc lp SqlRowUpdatingEventArgs, v Bng 11.13 cho thy nhng thuc tnh ca lp ny.
Bng 11.13: nhng thuc tnh SqlRowUpdatingEventArgs Thuc tnh Kiu M t Command SqlCommand Ly hay gn SqlCommand c chy khi phng thc Update() c gi. Errors Exception Ly ngoi l cho bt k li no xut hin. Row DataRow Ly DataRow gi ti c s d liu thng qua phng thc Update() . Thuc tnh Kiu M t StatementType StatementType Ly kiu ca pht biu SQL s c chy. StatementType l mt lit k trong namespace System.Data c cha nhng thnh vin sau y: Delete Insert Select Update Status UpdateStatus Ly hay gn UpdateStatus ca i tng Command. UpdateStatus l mt lit k trong namespace System.Data cha nhng thnh vin sau y: Continue :cho bit DataAdapter s tip tc vic x l nhng hng. ErrorsOccurred: cho bit s cp nht ny s c x l nh mt li. SkipAllRemainingRows: cho bit hng hin ti v tt c cc hng cn li u s c b qua v khng cp nht. SkipCurrentRow: cho bit hng hin thi ny s c b qua v khng cp nht. mc nh l Continue (tip tc).
TableMapping DataTableMapping Ly i tng DataTableMapping c gi ti phng thc Update() . Mt i tng DataTableMapping cha mt s m t v mt mi quan h c m hnh ha gia mt bng ngun v mt DataTable ( xem Chng 10, " S dng nhng i tng Dataset lu tr D liu ").
V d v B x l s kin sau y, c tn RowUpdatingEventHandler(), ngn nga bt k hng mi no c thm vo c s d liu vi mt CustomerID c tr l J5COM:
public static void RowUpdatingEventHandler( object sender, SqlRowUpdatingEventArgs mySRUEA ) { Console.WriteLine("\nIn RowUpdatingEventHandler()"); if ((mySRUEA.StatementType == StatementType.Insert) && (mySRUEA.Row["CustomerID"] == "J5COM")) { Console.WriteLine("Skipping current row"); mySRUEA.Status = UpdateStatus.SkipCurrentRow; } }
Bn ch nh mySqlDataAdapter s gi phng thc RowUpdatingEventHandler() khi s kin RowUpdating khi pht s dng m sau y
mySqlDataAdapter.RowUpdating += new SqlRowUpdatingEventHandler(RowUpdatingEventHandler);
Nu bn gi phng thc AddDataRow() c trnh by trc th thm mt hng vo bng Customers , s kin RowUpdating s khi pht v gi phng thc RowUpdatingEventHandler() . Phng thc ny lm cho hng mi b b qua v ngn nga n thm vo bng c s d liu Customers.
BIN C RowUpdate:
S kin RowUpdated khi pht sau khi mt hng c cp nht trong c s d liu nh mt kt qu ca vic gi phng thc Update() ca DataAdapter ca bn. S kin ny pht khi mt ln cho mi DataRow bn b sung, sa i, hay b xa mt DataTable.
Tham s th hai ti bt k phng thc no m bn vit x l s kin RowUpdated ca mt i tng SqlDataAdapter u thuc lp SqlRowUpdatedEventArgs . Nhng thuc tnh ca lp ny cng ging nh nhng thuc tnh trnh by trc y trong bng 11.13 , cng vi mt thuc tnh b sung trnh by trong Bng 11.14.
Bng 11.14: Thuc tnh SqlRowUpdatedEventArgs B sung Thuc tnh Kiu M t RecordsAffected int Ly mt int cha s lng hng c thm vo, sa i, hay loi b khi lnh (Command) thch hp c chy bi phng thc Update() .
v d v B x l s kin sau y, c tn RowUpdatedEventHandler(), n hin th s lng bn ghi b nh hng bi Command sau y:
Bn ch nh mySqlDataAdapter s gi phng thc RowUpdatedEventHandler() khi s kin RowUpdated khi pht s dng m sau y:
mySqlDataAdapter.RowUpdated += new SqlRowUpdatedEventHandler(RowUpdatedEventHandler);
NHNG S KIN DataTable:
Nhng s kin c pht khi t mt i tng DataTable c trnh by trong Bng 11.15.
Bng 11.15: nhng s kin DataTable S kin EVENT HANDLER M t ColumnChanging DataColumnChangeEventHandler Pht khi trc khi mt gi tr c thay i ca DataColumn c giao ph mt DataRow. ColumnChanged DataColumnChangeEventHandler Pht khi sau khi mt gi tr c thay i ca DataColumn c giao ph mt DataRow. RowChanging DataRowChangeEventHandler Pht khi trc khi mt DataRow c thay i, c giao ph mt DataTable. RowChanged DataRowChangeEventHandler Pht khi sau khi mt DataRow c thay i, c giao ph mt DataTable. RowDeleting DataRowChangeEventHandler Pht khi trc khi mt DataRow b xa t mt DataTable. RowDeleted DataRowChangeEventHandler Pht khi trc khi mt DataRow b xa t mt DataTable.
NHNG S KIN ColumnChanging V ColumnChanged:
Nhng s kin ColumnChanging pht khi trc khi mt s thay i ti mt gi tr DataColumn c giao ph mt DataRow. Tng t, nhng s kin ColumnChanged pht khi sau khi mt s thay i ti mt gi tr DataColumn c giao ph mt DataRow. Hai s kin ny lun c pht khi trc nhng s kin RowChanging v RowChanged.
T " Commit " trong vn cnh ny c ngha l g? Nu bn n gin t mt gi tr mi cho mt DataColumn, th s thay i c t ng c giao ph trong DataRow. Tuy nhin, nu bn bt u s thay i ti DataRow s dng phng thc BeginEdit() , th s thay i ch c giao ph khi bn gi phng thc EndEdit() ca DataRow ny. Bn cng c th loi b s thay i ti DataRow s dng phng thc CancelEdit() .
Tham s th hai ti bt k b x l s kin no m bn vit x l nhng s kin ColumnChanging hay ColumnChanged ca mt i tng DataTable iu thuc lp DataColumnChangeEventArgs. Bng 11.16 cho thy nhng thuc tnh (ca) lp ny.
Bng 11.16: nhng thuc tnh DataColumnChangeEventArgs Thuc tnh Kiu M t Column DataColumn Ly DataColumn vi gi tr m ang thay i. ProposedValue object Ly hay gn gi tr mi cho DataColumn. Row DataRow Ly DataRow cha DataColumn vi gi tr m ang thay i.
V d v nhng b s l phng thc sau y, c tn ColumnChangingEventHandler() v ColumnChangedEventHandler(), trnh by nhng thuc tnh Column v ProposedValue:
customersDataTable.ColumnChanging += new DataColumnChangeEventHandler(ColumnChangingEventHandler);
customersDataTable.ColumnChanged += new DataColumnChangeEventHandler(ColumnChangedEventHandler);
S KIN RowChanging V RowChanged:
S kin RowChanging khi pht trc khi mt s thay i ti mt DataRow c giao ph mt DataTable. Tng t, s kin RowChanged khi pht sau khi mt s thay i ti mt gi tr DataRow c giao ph mt DataTable.
Tham s th hai ti bt k b x l s kin no bn vit x l nhng s kin RowChanging hay RowChanged ca mt i tng DataTable u thuc lp DataRowChangeEventArgs. Bng 11.17 cho thy nhng thuc tnh (ca) lp ny.
Bng 11.17: nhng thuc tnh DataRowChangeEventArgs
Thuc tnh Kiu M t Action DataRowAction Ly DataRowAction xut hin cho DataRow. S lit k DataRowAction c nh ngha trong namespace System.Data v cha nhng thnh vin sau y: Add: cho bit DataRow c thm vo DataTable. Change: cho bit DataRow c sa i. Commit: cho bit DataRow c "giao ph" trong DataTable. Delete: cho bit DataRow c loi b t DataTable. Nothing: cho bit DataRow khng thay i. Rollback: cho bit s thay i ti DataRow c hy. Row DataRow Ly DataRow cha DataColumn vi gi tr ang thay i.
v d v nhng b x l s kin sau y, c tn RowChangingEventHandler() v RowChangedEventHandler(), hin th thuc tnh Action:
V d tip theo thm hai phng thc trc y ti nhng s kin RowChanging v RowChanged ca customersDataTable:
customersDataTable.RowChanging += new DataRowChangeEventHandler(RowChangingEventHandler);
customersDataTable.RowChanged += new DataRowChangeEventHandler(RowChangedEventHandler);
S KIN RowDeleting V RowDeleted:
S kin RowDeleting pht khi trc khi mt DataRow b xa t mt DataTable. Tng t, S kin RowDeleted khi pht sau khi mt DataRow b xa t mt DataTable.
Tham s th hai ti bt k b x l s kin no bn vit x l nhng s kin RowDeleting hay RowDeleted ca mt DataTable u thuc lp DataRowChangeEventArgs, v Bng 11.17 trc cho thy nhng thuc tnh ca lp ny.
V d v nhng " b iu khin phng thc" sau y, c tn RowDeletingEventHandler() v RowDeleted- EventHandler(), trnh by thuc tnh Action:
V d k tip thm hai phng thc trc ti nhng s kin RowDeleting v RowDeleted ca customersDataTable:
customersDataTable.RowDeleting += new DataRowChangeEventHandler(RowDeletingEventHandler);
customersDataTable.RowDeleted += new DataRowChangeEventHandler(RowDeletedEventHandler);
Ghi nh: Bn s tm thy tt c m nhng v d trnh by trong mc ny trong chng trnh UsingEvents.cs nh v trong th mc ch11. Danh sch chng trnh ny c b qua trong sch ny cho ngn gn.
GII QUT NHNG S THT BI CP NHT:
Cho n lc ny, nhng v d bn thy u gi thit rng nhng s cp nht y ti c s d liu bi phng thc Update() u thnh cng. Trong mc ny, bn s thy nhng g xy ra khi nhng s cp nht tht bi - v nhng g bn c th lm v iu ny.
Ghi nh : Bn s tm thy tt c m v d trnh by trong mc ny trong tp tin HandlingUpdateFailures.cs c nh v trong th mc ch11. Danh sch chng trnh ny c b qua trong sch ny cho ngn gn.
Trong nhng v d trong mc ny, gi thit rng thuc tnh CommandText ca mt UpdateCommand ca i tng SqlDataAdapter c thit t nh sau:
UPDATE Customers SET CompanyName = @NewCompanyName, Address = @NewAddress WHERE CustomerID = @OldCustomerID AND CompanyName = @OldCompanyName AND Address = @OldAddress
Pht biu Update ny s dng s "tng tranh lc quan" bi v nhng ct c cp nht bao gm trong mnh WHERE.
MT TNH HUNG THT BI CP NHT:
Xem xt tnh hung sau y trnh by mt s tht bi cp nht:
1. Ngi s dng 1 truy xut nhng hng t bng Customers vo trong mt DataTable c tn customersDataTable. 2. Ngi s dng 2 cng truy xut cng hng ny. 3. Ngi s dng 1 cp nht ct d liu CustomerName ca DataRow vi ct kha chnh CustomerID l J5COM v y s thay i ti c s d liu. Cho l ngi s dng 1 thay i CustomerName t J5 Company n Updated Company. 4. Ngi s dng 2 cng cp nht cng DataRow ny v thay i CompanyName t J5 Company n Widgets Inc. v n lc y s thay i ny ti c s d liu. nh vy ngi s dng 2 gy cho mt i tng DBConcurrecy- Exception s c nm ra v s cp nht ca h tht bi. (Ngoi l ging nh vy xut hin nu ngi s dng 2 th cp nht hay xa mt hng m b xa bi ngi s dng 1.)
Ti sao s cp nht trong bc 4 b tht bi ? L do l vi s tng tranh lc quan, ct CompanyName c s dng trong mnh WHERE ca pht biu Update. Bi v iu ny, hng nguyn bn c ti bi ngi s dng 2 khng th tm thy na - v do pht biu cp nht tht bi. Hng khng th tm c v ngi s dng 1 thay i ct CompanyName t J5 Company n Updated Company trong bc 2.
y l vn vi s "tng tranh lc quan", nhng iu g m Bn c th lm nh mt ngi lp trnh ? Bn c th bo co s c ti ngi s dng 2, lm ti li nhng hng ca h s dng phng thc Fill(), h c th thc hin s thay i ca h ln na - tuy nhin, nu ngi s dng 2 thc rt hin nhiu ln s thay i v h cng khng th lu tr bt k th g ca h, h c l s rt bt mn v chng trnh ca bn.
May mn thay, bn c th t thuc tnh ContinueUpdateOnError ca DataAdapter ca bn l true tip tc cp nht bt k i tng DataRow no d mt li xut hin. vi cch ny, khi ngi s dng 2 lu nhng s thay i ca h , h c th t nht lu c nhng hng m khng gy ra bt k li no. Chng ta hy xem xt cch thit t thuc tnh ContinueUpdateOnError nh th no.
THIT T THUC TNH ContinueUpdateOnError:
V d sau y t thuc tnh ContinueUpdateOnError ti true cho mySqlDataAdapter:
mySqlDataAdapter.ContinueUpdateOnError = true;
Khi bn gi mySqlDataAdapter.Update(), n s y tt c nhng s thay i m khng gy ra nhng li ti c s d liu.v Bn c th kim tra nhng li sau s dng thuc tnh HasErrors ca mt Dataset hay thuc tnh HasErrors ca nhng i tng DataTable ring l, nhng li m Bn s thy khng lu sau y trong mc " S kim tra nhng li."
LP TRNH MT V D CP NHT THT BI:
Chng ta hy lp trnh mt v d v mt s cp nht b tht bi. V d ny s m phng nhng s cp nht gy ra bi ngi s dng 1 v ngi s dng 2 m t trc . Ti s s dng phng thc sau y, c tn ModifyRowsUsingUPDATE(), m phng s cp nht thc hin bi ngi s dng 1 trong bc 3 m t trc
public static void ModifyRowUsingUPDATE( SqlConnection mySqlConnection ) { Console.WriteLine("\nIn ModifyDataRowUsingUPDATE()"); Console.WriteLine("Updating CompanyName to 'Updated Company' for J5COM");
// step 1: set the PrimaryKey property of the DataTable myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns["CustomerID"] };
// step 2: use the Find() method to locate the DataRow // in the DataTable using the primary key value DataRow myDataRow = myDataTable.Rows.Find("J5COM");
// step 3: change the DataColumn values of the DataRow myDataRow["CompanyName"] = "Widgets Inc."; Console.WriteLine("myDataRow.RowState = " + myDataRow.RowState);
// step 4: use the Update() method to push the modified // row to the database Console.WriteLine("Calling mySqlDataAdapter.Update()"); mySqlConnection.Open(); int numOfRows = mySqlDataAdapter.Update(myDataTable); mySqlConnection.Close(); Console.WriteLine("numOfRows = " + numOfRows); Console.WriteLine("myDataRow.RowState = " + myDataRow.RowState);
DisplayDataRow(myDataRow, myDataTable); }
V d k tip gi ModifyRowUsingUPDATE() thc hin s cp nht u tin ca hng vi CustomerID l J5COM:
ModifyRowUsingUPDATE(mySqlConnection);
Tip theo, thuc tnh ContinueUpdateOnError ca mySqlDataAdapter c gn l true tip tc cp nht bt k i tng DataRow no d mt li xy ra
mySqlDataAdapter.ContinueUpdateOnError = true;
Tip theo, ModifyDataRow() c gi th sa i cng mt hng nh ModifyRowsUsingUPDATE():
Thng thng, iu ny s nm ra mt ngoi l v hng ny khng th tm thy c, nhng do thuc tnh ContinueUpdateOnError ca mySqlDataAdapter c thit lp ti true, khng c ngoi l c nm ra. Bng cch ny, nu myDataTable c nhng hng c cp nht khc, chng s vn c y ti c s d liu bi s gi ti phng thc Update() .
KIM TRA NHNG LI:
Khi thuc tnh ContinueUpdateOnError ca mySqlDataAdapter c gn ti true, s khng c ngoi l c nm khi mt li xut hin. Thay vo , bn c th kim tra nhng li trong mt Dataset hay DataTable ring r hay DataRow s dng thuc tnh HasErrors. ri Bn c th hin th cho ngi s dng, nhng chi tit ca li ,s dng thuc tnh RowError ca DataRow, Cng vi nguyn bn v nhng gi tr hin ti cho nhng i tng DataColumn trong DataRow . v d:
if (myDataSet.HasErrors) { Console.WriteLine("\nDataSet has errors!"); foreach (DataTable myDataTable in myDataSet.Tables) { // check the HasErrors property of myDataTable if (myDataTable.HasErrors) { foreach (DataRow myDataRow in myDataTable.Rows) { // check the HasErrors property of myDataRow if (myDataRow.HasErrors) { Console.WriteLine("Here is the row error:"); Console.WriteLine(myDataRow.RowError); Console.WriteLine("Here are the column details in the DataSet:"); foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "original value = " + myDataRow[myDataColumn, DataRowVersion.Original]); Console.WriteLine(myDataColumn + "current value = " + myDataRow[myDataColumn, DataRowVersion.Current]); } } } } } }
CHNH L LI:
Hin th li cho ngi s dng ch l na cng vic. Bn c th lm g chnh nh vn ? Mt gii php l gi phng thc Fill() ln na ng b ha nhng hng trong Dataset ca bn vi c s d liu. bng cch ny, hng c cp nht bi ModifyRowsUsingUPDATE() trong bng Customers s c ko t bng Customers v thay th hng nguyn bn J5COM trong Dataset. Chng hn:
Bn c l mong i numOfRows s l 1, bi v Bn ang thay th ch mt hng, ng ? sai : numOfRows s cha tng s lng hng trong bng Customers . L do cho iu ny l phng thc Fill() tht s ko tt c nhng hng t bng Customers v t chng trong DataTable Customers ca myDataSet, n vt b bt k hng hin hu no c gi tr ct kha chnh ph hp c trong DataTable Customers.
Cnh bo: Nu bn khng thm mt kha chnh vo DataTable Customers ca bn , th s gi ti phng thc Fill() ch n gin l thm tt c nhng hng t bng Customers n DataTable Customers ln na- s trng lp nhng hng sy ra y.
Tip theo, bn gi ModifyDataRow() ln na iu chnh hng J5COM :
Ln ny s cp nht thnh cng v ModifyDataRow() tm kim hng J5COM trong customersDataTable m va c ko v t bng Customers.
Ghi nh: nu mt ngi s dng c cp nht mt hng b xa t bng c s d liu, th iu duy nht bn c th lm l lm mi (refresh) li nhng hng v yu cu ngi s dng cp nht li hng ca h ln na.
S DNG Transaction(NHNG GIAO DCH) VI MT Dataset(SQL):
Trong Chng 3, " gii thiu Ngn ng truy vn c cu trc", bn thy cch nhm nhng cu lnh SQL cng nhau nh th no vo trong transactions (giao dch).ri transaction c giao ph hay hi phc nh mt n v. Chng hn, trong trng hp ca mt giao dch ngn hng bn c l mun rt tin t mt ti khon v chuyn vo trong ti khon khc. ri Bn giao ph c hai s thay i ny nh mt n v, hoc nu sy ra mt vn , hi phc li c hai thay i. Trong Chng 8, " thc hin nhng lnh C s d liu ", bn thy cch s dng mt i tng transaction (Giao dch) nh th no i din cho mt Giao dch.
Nh bn bit, mt Dataset khng c mt s ni kt trc tip ti c s d liu. Thay vo , bn s dng nhng phng thc Fill() v Update() tng ng ca mt DataAdapter ko v y nhng hng t v ti c s d liu vo Dataset ca bn . Tht ra, mt Dataset khng c cht " kin thc " no v c s d liu . Mt Dataset n gin ct gi mt bn sao khng kt ni ca d liu. V iu ny, mt Dataset khng c bt k chc nng gn sn no x l nhng giao dch.
ri Bn s dng nhng giao dch vi mt Dataset nh th no? Cu tr li l bn phi s dng thuc tnh Transaction ca nhng i tng Command c ct gi trong mt DataAdapter.
S DNG THUC TNH TRANSACTION CA I TNG DataAdapter Command
Mt DataAdapter ct gi bn i tng Command (Lnh) m khi bn truy nhp s dng nhng thuc tnh SelectCommand, InsertCommand, UpdateCommand, v DeleteCommand. Khi bn gi phng thc Update() ca mt DataAdapter, n s chy InsertCommand, UpdateCommand, hay DeleteCommand thch hp.
Bn c th to ra mt i tng Giao dch (Transaction) v thuc tnh Transaction ca nhng i tng Command trong DataAdapter ca bn c gn vi Transaction ny. ri khi bn sa i Dataset ca bn v y nhng s thay i ti c s d liu s dng phng thc Update() ca DataAdapter ca bn, Nhng s thay i s s dng cng mt Transation.
V d sau y to ra mt i tng SqlTransaction c tn mySqlTransaction v gn thuc tnh Transaction ca ton b nhng i tng Command trong mySqlDataAdapter ti mySqlTransaction:
Ton b nhng i tng Command trong mySqlDataAdapter by gi s s dng mySqlTransaction. Chng ta hy cho l bn thm, iu chnh, v loi b mt s hng t mt DataTable c cha trong mt Dataset c tn myDataSet. Bn c th y nhng s thay i ny ti c s d liu s dng v d sau y:
mySqlDataAdapter.Update(myDataSet);
Tt c nhng s thay i ca cc bn ti myDataSet c y ti c s d liu nh b phn ca giao dch trong mySqlTransaction. Bn c th giao ph nhng s thay i s dng phng thc Commit() ca mySqlTransaction:
Bn c th cng phc nguyn nhng s thay i s dng phng thc Rollback() ca mySqlTransaction.
Ghi ch: Mt giao dch l phc nguyn theo mc nh; bi vy, bn cn phi lun lun ch nh r rng l giao ph hay phc nguyn giao dch ca bn, s dng Commit() hay Rollback() n thc hin ng ci m chng trnh ca bn d nh lm.
SA I D LIU S DNG MT Dataset NH KIU D LIU MNH
Trong Chng 10, bn thy cch to v s dng mt lp Dataset nh kiu d liu mnh c tn MyDataSet nh th no. Bn c th s dng nhng i tng ca lp ny i din cho bng Customers v nhng hng t bng ny. Trong mc ny, bn s thy cch sa i d liu nh th no s dng mt i tng nh kiu mnh ca lp MyDataSet.
Ghi ch Mt trong s nhng c tnh ca mt i tng Dataset nh kiu mnh cho php bn c mt gi tr ct s dng mt thuc tnh c cng tn vi ct. Chng hn, c CustomerID ca mt ct bn c th s dng myDataRow. CustomerID thay v myDataRow[ " CustomerID "]. Xem Chng 10 cho nhiu chi tit v c gi tr ct hn.
Ba phng thc sau y trong lp MyDataSet cho php bn sa i nhng hng c ct gi trong mt i tng MyDataSet gm : NewCustomersRow(), AddCustomersRow(), v RemoveCustomersRow(). Bn c th tm thy mt hng s dng phng thc FindByCustomerID() . Bn c th kim tra liu mt gi tr ct cha ng mt gi tr null s dng nhng phng thc nh IsContactNameNull(), v Bn c th t mt ct ti null s dng nhng phng thc nh SetContactNameNull(). Bn s thy cch s dng phng thc ny khng lu say y.
Phng thc Form1_Load() ca Form trong d n v d trnh by cch thm, sa i, v loi b mt hng ti mt i tng Dataset kiu d liu mnh c tn myDataSet1. Bn s thy nhng bc hon thnh nhng nhim v ny trong phng thc Form1_Load() sau :
private void Form1_Load(object sender, System.EventArgs e) { // populate the DataSet with the CustomerID, CompanyName, // and Address columns from the Customers table sqlConnection1.Open(); sqlDataAdapter1.Fill(myDataSet1, "Customers");
// get the Customers DataTable MyDataSet.CustomersDataTable myDataTable = myDataSet1.Customers;
// create a new DataRow in myDataTable using the // NewCustomersRow() method of myDataTable MyDataSet.CustomersRow myDataRow = myDataTable.NewCustomersRow();
// set the CustomerID, CompanyName, and Address of myDataRow myDataRow.CustomerID = "J5COM"; myDataRow.CompanyName = "J5 Company"; myDataRow.Address = "1 Main Street";
// add the new row to myDataTable using the // AddCustomersRow() method myDataTable.AddCustomersRow(myDataRow);
// push the new row to the database using // the Update() method of sqlDataAdapter1 sqlDataAdapter1.Update(myDataTable);
// find the row using the FindByCustomerID() // method of myDataTable myDataRow = myDataTable.FindByCustomerID("J5COM"); // modify the CompanyName and Address of myDataRow myDataRow.CompanyName = "Widgets Inc."; myDataRow.Address = "1 Any Street";
// push the modification to the database sqlDataAdapter1.Update(myDataTable);
// display the DataRow objects in myDataTable // in the listView1 object foreach (MyDataSet.CustomersRow myDataRow2 in myDataTable.Rows) { listView1.Items.Add(myDataRow2.CustomerID); listView1.Items.Add(myDataRow2.CompanyName);
// if the Address is null, set Address to "Unknown" if (myDataRow2.IsAddressNull() == true) { myDataRow2.Address = "Unknown"; } listView1.Items.Add(myDataRow2.Address); }
// find and remove the new row using the // FindByCustomerID() and RemoveCustomersRow() methods // of myDataTable myDataRow = myDataTable.FindByCustomerID("J5COM"); myDataTable.RemoveCustomersRow(myDataRow);
// push the delete to the database sqlDataAdapter1.Update(myDataTable);
sqlConnection1.Close(); }
Hy thai mi bin tp v chy form v d.
TM TT:
Trong chng ny, bn hc cch sa i nhng hng trong mt Dataset v sau y nhng s thay i ti c s d liu qua mt DataAdapter nh th no.
Bn thy cch thm nhng s hn ch vo mt DataTable v nhng i tng DataColumn ca n nh th no. iu ny cho php bn m hnh nhng s hn ch tng t da trn nhng bng c s d liu v nhng ct trong nhng i tng DataTable v DataColumn ca bn. Bi vic thm nhng s hn ch ln trn v pha trc, bn ngn nga d liu xu c thm vo Dataset ca bn , v nhng tr gip ny gim bt nhng li khi th y nhng thay i trong Dataset ca bn ti c s d liu.
Mi hng trong mt DataTable c ct gi trong mt i tng DataRow, v bn thy cch tm , lc, v phn loi nhng i tng DataRow mt DataTable s dng phng thc Find() ca mt DataTable nh th no. Bn cng hc cch lc v phn loi nhng i tng DataRow mt DataTable nh th no s dng phng thc Select() .
Bn thy nhng bc c yu cu thm, sa i, v loi b nhng i tng DataRow t mt DataTable v sau y nhng thay i ny n c s d liu. lm iu ny u tin bn phi thit lp DataAdapter ca bn vi nhng i tng Command cha nhng pht biu SQL INSERT, UPDATE, v DELETE tng ng . Bn ct gi nhng i tng Command ny trong nhng thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca i tng DataAdapter ca bn. Bn y nhng thay i t Dataset ca bn n c s d liu s dng phng thc Update() ca DataAdapter ca bn. Khi bn thm, iu chnh, hay loi b nhng i tng DataRow t Dataset ca bn v sau gi phng thc Update() ca DataAdapter ca bn , InsertCommand, UpdateCommand, hay DeleteCommand thch hp c chy y nhng thay i ca bn ti c s d liu.
S Tng tranh xc nh nhng s sa i ca nhiu ngi s dng ti cng hng c x l nh th no. Vi s tng tranh lc quan, bn c th sa i mt hng trong mt bng c s d liu ch khi khng ai khc sa i chnh hng t khi bn ti n vo trong Dataset ca cc bn. y l kiu tng tranh in hnh tt nht s dng bi v bn khng mun ghi nhng s thay i ca mt ngi khc . Vi s tng tranh " ngi trc thng " , bn lun lun c th sa i mt hng- v nhng s thay i ca bn ghi ln nhng s thay i bt c ai khc. Bn in hnh mun trnh s dng s tng tranh " ngi trc thng " .
Bn c th c mt i tng DataAdapter gi nhng th tc lu tr thm, sa i, v loi b nhng hng t c s d liu. Nhng th tc ny c gi (thay cho nhng pht biu Chn, Cp nht, v Xa) v bn c thy cch thit t nhng thuc tnh InsertCommand, UpdateCommand, V DeleteCommand ca mt i tng DataAdapter .
Vic cung cp nhng pht biu Chn, Cp nht v Xa hay nhng th tc c lu tr ca bn y nhng thay i t Dataset ca bn n c s d liu c ngha l bn phi vit nhiu m. Bn c th trnh vit m ny bi vic s dng mt i tng CommandBuilder, n c th t ng pht sinh nhng pht biu Chn , Cp nht, v xa bng n y nhng thay i Bn lm vi mt i tng Dataset ti c s d liu. Nhng lnh ny s c gn trong thuc tnh InsertCommand, UpdateCommand, v DeleteCommand ca i tng DataAdapter ca bn .
Bn cng thy cch x l nhng s tht bi cp nht v s dng nhng giao dch vi mt Dataset nh th no, v trong mc cui cng ca chng ny Bn thy cch cp nht nhng hng c ct gi trong mt Dataset kiu d liu mnh nh th no.
Trong Chng 12, bn s hc cch nh hng v sa i d liu lin quan nh th no.
CHNG 12: NH HNG V SA I D LIU LIN H:
Tng quan Trong chng 2, " Gii thiu v nhng c s d liu, " Bn thu sut nhng bng c s d liu lin quan ln nhau thng qua nhng kha ngai. Chng hn, ct OrderID ca bng Orders lin quan n ct CustomerID ca bng Customers thng qua mt kha ngai. V bng Ordres ph thuc vo bng Customers, Bng Orders c hiu nh bng con v bng Customers nh bng cha . Kha ngai c ni ti nh ngha mt mi quan h cha con gia hai bng.
Trong chng ny, bn s i su vo trong nhng chi tit ca nhng i tng UniqueConstraint, ForeignKeyConstraint, v DataRelation . Bn s cng xem xt cch nh hng nhng hng trong nhng i tng DataTable lin quan, thc hin nhng thay i trong nhng i tng DataTable lin quan , v cui cng y nhng s thay i ti c s d liu.
Mo nh: ci thin s thc hin khi ti mt DataTable vi mt lng ln i tng DataRow , bn cn phi t thuc tnh EnforceConstraints ca Dataset ca bn l false cho khong thi gian ca s ti. iu ny ngt b nhng s rng buc bt buc. Nh gn EnforceConstraints tr v gi tr mc nh true cui qu trnh ti.
Nhng ch im trong chng ny: Lp UniqueConstraint To ra mt i tng UniqueConstraint Lp ForeignKeyConstraint To ra mt i tng ForeignKeyConstraint Lp DataRelation To v s dng mt i tng DataRelation Thm, cp nht, v xa nhng hng lin quan Nhng vn khi cp nht kha chnh ca mt hng cha Mng XML nh ngha mt mi quan h s dng Visual Studio .NET
LP UniqueConstraint: Bn s dng mt i tng ca lp UniqueConstraint bo m l gi tr mt DataColumn , hay s kt hp ca nhng gi tr DataColumn, l duy nht cho mi DataRow mt DataTable. Lp UniqueConstraint c bt ngun t lp System.Data.Constraint . Bng 12.1 cho thy nhng thuc tnh UniqueConstraint.
Bng 12.1: nhng thuc tnh UniqueConstraint Thuc tnh kiu d liu M t Columns DataColumn[] Ly mng ca nhng i tng DataColumn cho UniqueConstraint. ConstraintName string Ly tn ca UniqueConstraint. ExtendedProperties PropertyCollection Ly i tng PropertyCollection m bn c th s dng ct gi nhng chui ca thng tin b sung. IsPrimaryKey bool Ly mt gi tr bool cho bit liu c phi UniqueConstraint l mt kha chnh. Table DataTable Ly DataTable trong UniqueConstraint c to ra.
TO MT I TNG UniqueConstraint:
Trong mc ny, bn s hc cch to ra mt i tng UniqueConstraint nh th no. B khi to UniqueConstraint c ti nh sau:
vi : myDataColumn v myDataColumns l nhng i tng DataColumn m bn mun bo m duy nht. constraintName l tn bn mun gn ti thuc tnh ConstraintName ca UniqueConstraint ca bn. isPrimaryKey cho bit liu c phi UniqueConstraint ca bn thuc mt kha chnh.
Trc khi to ra v thm mt UniqueConstraint ti mt DataTable, u tin Bn cn mt DataTable. V d sau y to ra v c tr hai i tng DataTable c tn customersDT v ordersDT ( i tng ordersDT s c s dng sau trong mc "To ra mt i tng ForeignKeyConstraint"):
V d sau y to ra mt i tng UniqueConstraint trn DataColumn CustomerID ca customersDT DataTable, V sau thm UniqueConstraint ny vo customersDT; ch tham s th ba ti B khi dng UniqueConstraint c gn l true, cho bit s rng buc l cho mt kha chnh:
UniqueConstraint myUC = new UniqueConstraint( "UniqueConstraintCustomerID", customersDT.Columns["CustomerID"], true ); customersDT.Constraints.Add(myUC);
Ghi ch thm mt cch thnh cng mt UniqueConstraint vo DataColumn ca mt DataTable, gi tr DataColumn trong mi i tng DataRow trong DataTable phi l duy nht.
V d cui cng truy xut s rng buc va thm vo customerDT v hin th nhng thuc tnh ca n:
V d ny trnh by u ra sau y Columns: CustomerID myUC.ConstraintName = UniqueConstraintCustomerID myUC.IsPrimaryKey = True myUC.Table = Customers Thuc tnh IsPrimaryKey l true bi v s rng buc thuc mt kha chnh; iu ny c ch r trong b khi to khi s rng buc c to ra trc .
LP Foreignkey Constraint:
Bn s dng mt i tng ca lp ForeignKeyConstraint i din cho mt s rng buc kha ngoi gia hai i tng DataTable. iu ny bo m rng mi DataRow trong DataTable con c mt DataRow thch ng trong DataTable cha ca bn. Lp ForeignKeyConstraint c bt ngun t lp System.Data.Constraint . Bng 12.2 cho thy nhng thuc tnh ForeignKeyConstraint.
Bng 12.2: nhng thuc tnh ForeignKeyConstraint Thuc tnh Kiu d liu M t AcceptRejectRule AcceptRejectRule Ly hay gn AcceptRejectRule cho bit hot ng s xy ra khi phng thc AcceptChanges() ca DataTable c gi . Nhng thnh vin ca S lit k System.Data.AcceptRejectRule l: Cascade: cho bit nhng s thay i ti nhng i tng DataRow trong DataTable cha cng c lm trong DataTable con None : cho bit khng c hot ng no xy ra. Mc nh l None. Columns DataColumn[] Ly mng ca nhng i tng DataColumn t DataTable con. ConstraintName string Ly tn ca i tng UniqueConstraint. DeleteRule Rule Ly hay gn quy tc cho bit hot ng s xy ra khi mt DataRow trong DataTable cha b xa. Nhng thnh vin ca s lit k System.Data.Rule l: Cascade, cho bit s xa hay cp nht ti nhng i tng DataRow trong DataTable cha cng c thc hin trong DataTable con. None: cho bit khng c hot ng no xy ra. SetDefault: cho bit rng nhng gi tr DataColumn trong DataTable con s c thit lp ti gi tr trong thuc tnh DefaultValue ca DataColumn. SetNull: cho bit nhng gi tr DataColumn trong DataTable con s c thit lp ti DBNull. gi tr mc nh l Cascade. ExtendedProperties PropertyCollection Ly i tng PropertyCollection m bn c th s dng lu tr nhng chui ca thng tin b sung. RelatedColumns DataColumn[] Ly mng ca nhng i tng DataColumn trong DataTable cha cho UniqueConstraint. RelatedTable DataTable Ly DataTable cha DataTable cho UniqueConstraint. Table DataTable Ly DataTable con m UniqueConstraint thuc v. UpdateRule Rule Ly hay gn quy tc cho bit hot ng s xy ra khi mt DataRow trong DataTable cha c cp nht. Xem thuc tnh DeleteRule v nhng thnh vin ca s lit k quy tc (Rule enumeration) . mc nh l Cascade.
Vi : . parentDataColumn v parentDataColumns l nhng i tng DataColumn trong DataTable cha . . childDataColumn v childDataColumns l nhng i tng DataColumn trong DataTable con . . constraintName l tn bn mun gn ti thuc tnh ConstraintName ca ForeignKeyConstraint ca cc bn. . parentDataTableName l tn ca DataTable cha. . parentDataColumnNames v childDataColumnNames cha tn ca nhng i tng DataColumn trong nhng i tng DataTable cha v con. . acceptRejectRule, deleteRule, v updateRule l nhng quy tc cho ForeignKey- Constraint.
Trc trong mc "To ra mt i tng UniqueConstraint," bn thy mt v d m to ra hai i tng DataTable c tn customersDT v ordersDT. V d sau y to ra mt i tng ForeignKeyConstraint trn DataColumn CustomerID ca ordersDT ti DataColumn CustomerID ca customersDT:
ForeignKeyConstraint myFKC = new ForeignKeyConstraint( "ForeignKeyConstraintCustomersOrders", customersDT.Columns["CustomerID"], ordersDT.Columns["CustomerID"] ); ordersDT.Constraints.Add(myFKC);
Ch : ForeignKeyConstraint c thm vo ordersDT s dng phng thc Add(). Ghi ch: thm mt cch thnh cng mt ForeignKeyConstraint vo mt DataTable, mi gi tr DataColumn trong DataTable con phi c mt gi tr DataColumn thch ng trong DataTable cha. v d k tip truy xut s rng buc va thm vo ordersDT v trnh by nhng thuc tnh ca n :
myFKC.AcceptRejectRule = None Columns: CustomerID myFKC.ConstraintName = ForeignKeyConstraintCustomersOrders myFKC.DeleteRule = Cascade RelatedColumns: CustomerID myFKC.RelatedTable = Customers myFKC.Table = Orders myFKC.UpdateRule = Cascade Ghi ch Bn s tm thy tt c m nhng v d trnh by trong mc ny v mc trc y, "To ra mt i tng UniqueConstraint, " trong chng trnh AddConstraints.cs . chng trnh ny b b qua trong sch ny cho ngn gn.
LP DataRelation:
Bn s dng mt i tng ca lp DataRelation i din cho mt mi quan h gia hai i tng DataTable. Bn s dng mt i tng DataRelation m hnh nhng mi quan h cha - con gia hai bng c s d liu. Theo mc nh, khi bn to ra mt DataRelation- mt UniqueConstraint v ForeignKeyConstraint c t ng thm vo nhng i tng DataTable cha v con ca cc bn . Bng 12.3 cho thy nhng thuc tnh DataRelation.
Bng 12.3: nhng thuc tnh DataRelation Thuc tnh Kiu d liu M t ChildColumns DataColumn[] Ly mng ca nhng i tng DataColumn con. ChildKeyConstraint ForeignKeyConstraint Gets the ForeignKeyConstraint object for the DataRelation. ly i tng ForeignKeyConstraint cho DataRelation. ChildTable DataTable Ly i tng DataTable con. DataSet DataSet Ly Dataset m DataRelation thuc v. ExtendedProperties PropertyCollection Ly i tng PropertyCollection m bn c th dng ct gi nhng chui ca thng tin b sung. Nested bool Ly hay gn mt gi tr bool cho bit liu c phi nhng i tng DataRelation c lng vo.iu ny hu ch khi nh ngha nhng mi quan h c th bc trong XML. Mc nh l false. ParentColumns DataColumn[] Ly mng ca nhng i tng DataColumn cha . ParentKeyConstraint UniqueConstraint Ly i tng UniqueConstraint m bo m rng nhng gi tr DataColumn trong DataTable cha l duy nht. ParentTable DataTable Ly i tng DataTable cha . RelationName string Ly tn ca i tng DataRelation.
TO V S DNG MT I TNG DataRelation:
Trong mc ny, bn s hc cch to ra mt i tng DataRelation nh ngha mt mi quan h gia hai i tng DataTable m gi mt s hng t bng Customers v Orders . Nh bn bit, ct CustomerID ca bng Orders con l mt kha ngoi lin kt ti ct CustomerID ca bng Customers cha. Mt khi bn to ra mt DataRelation, bn c th s dng phng thc GetChildRows() ca mt i tng DataRow trong DataTable cha thu c nhng i tng DataRow tng ng t DataTable con . Vi t " tng ng ", Ti nh ngha nhng hng ph hp vi nhng gi tr trong nhng i tng DataColumn kha ngoi. Bn c th cng s dng phng thc GetParentRow() ca mt DataRow trong DataTable con thu c DataRow tng ng trong DataTable cha . Trc khi to ra v thm mt DataRelation vo mt Dataset, u tin bn cn mt Dataset. V d theo sau to ra v c tr mt Dataset vi hai i tng DataTable t tn customersDT v ordersDT; ch hai hng u tin t bng Customers cng vi nhng hng tng ng t bng Orders c truy xut: SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 CustomerID, CompanyName " + "FROM Customers " + "ORDER BY CustomerID;" + "SELECT OrderID, CustomerID " + "FROM Orders " + "WHERE CustomerID IN (" + " SELECT TOP 2 CustomerID " + " FROM Customers " + " ORDER BY CustomerID" + ")"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet); mySqlConnection.Close(); myDataSet.Tables["Table"].TableName = "Customers"; myDataSet.Tables["Table1"].TableName = "Orders"; DataTable customersDT = myDataSet.Tables["Customers"]; DataTable ordersDT = myDataSet.Tables["Orders"];
Bn s thy cch to ra mt DataRelation nh ngha mt mi quan h gia nhng i tng DataTable: customersDT v ordersDT nh th no . Ghi ch: Bn s tm thy tt c nhng m v d trnh by trong mc ny trong chng trnh CreateDataRelation.cs .
TO RA MT DataRelation: B khi dng DataRelation c qu ti nh sau: DataRelation(string dataRelationName, DataColumn parentDataColumn, DataColumn childDataColumn) DataRelation(string dataRelationName, DataColumn[] parentDataColumns, DataColumn[] childDataColumns) DataRelation(string dataRelationName, DataColumn parentDataColumn, DataColumn childDataColumn, bool createConstraints) DataRelation(string dataRelationName, DataColumn[] parentDataColumns, DataColumn[] childDataColumns, bool createConstraints) DataRelation(string dataRelationName, string parentDataTableName, string childDataTableName, string[] parentDataColumnNames, string[] childDataColumnNames, bool nested)
Vi : . dataRelationName l tn bn mun gn ti thuc tnh RelationName ca DataRelation ca bn. . parentDataColumn v i tng DataColumn parentDataColumnsare trong DataTable cha . . childDataColumn v childDataColumns l nhng i tng DataColumn trong DataTable con . . createConstraints cho bit liu bn c mun mt UniqueConstraint c thm vo DataTable cha v mt ForeignKeyConstraint c thm vo DataTable con mt cch t ng (mc nh l true) . parentDataTableName v childDataTableName l nhng tn ca nhng i tng DataTable cha v con. . parentDataColumnNames v childDataColumnNames cha tn ca nhng i tng DataColumn trong nhng i tng DataTable cha v con . . nested : cho bit liu c phi nhng mi quan h c lng vo.
V d sau y to ra mt i tng DataRelation c tn customersOrdersDataRel:
DataRelation customersOrdersDataRel = new DataRelation( "CustomersOrders", customersDT.Columns["CustomerID"], ordersDT.Columns["CustomerID"] );
Tn c gn ti thuc tnh RelationName ca customersOrdersDataRel l CustomersOrders, DataColumn cha l customersDT.Columns[ " CustomerID "], v DataColumn con l ordersDT.Columns[ " CustomerID "]. Tip theo, customersOrdersDataRel phi c thm vo myDataSet. Bn truy nhp nhng i tng DataRelation trong mt i tng Dataset thng qua thuc tnh Relationships ca n. Thuc tnh Relationships tr li mt i tng ca lp DataRelationCollection, l mt tp hp ca nhng i tng DataRelation. thm mt i tng DataRelation vo i tng DataRelationCollection ca mt Dataset, bn gi phng thc Add() thng qua thuc tnh Relationships ca Dataset ca bn.
V d sau y s dng phng thc Add() thm customersOrdersDataRel ti myDataSet:
myDataSet.Relations.Add( customersOrdersDataRel ); Phng thc Add() c qu ti, v bn cng c th s dng phin bn sau ca phng thc Add() to ra v thm mt i tng DataRelation ti myDataSet:
V d ny thc hin cng cng vic nh vi hai v d v d trc. Tham s u tin ti phng thc Add() l mt chui cha tn bn mun gn ti thuc tnh RelationName ca DataRelation. Nhng tham s th hai v ba ca mi quan h l nhng i tng DataColumn t nhng i tng DataTable cha v con.
KHO ST NHNG S RNG BUC TO RA BI DataRelation: Theo mc nh, khi bn to ra mt DataRelation, mt UniqueConstraint v ForeignKeyConstraint c t ng thm vo nhng i tng DataTable cha v con ca bn. Bn c th ly UniqueConstraint t mt DataRelation s dng thuc tnh ParentKeyConstraint ca n. Chng hn:
Bn c th ly ForeignKeyConstraint t mt DataRelation s dng thuc tnh ChildKeyConstraint ca n. Chng hn: ForeignKeyConstraint myFKC = customersOrdersDataRel.ChildKeyConstraint;
Bn c th xem nhng thuc tnh ca myFKC s dng m sau y :
u ra t m ny nh sau: myFKC.AcceptRejectRule = None Columns: CustomerID myFKC.ConstraintName = CustomersOrders myFKC.DeleteRule = Cascade RelatedColumns: CustomerID myFKC.RelatedTable = Customers myFKC.Table = Orders myFKC.UpdateRule = Cascade
Thuc tnh DeleteRule v UpdateRule c gn ti Cascade theo mc nh. V DeleteRule c gn ti Cascade, khi bn xa mt DataRow trong DataTable cha , th bt k i tng DataRow tng ng no trong DataTable con u cng b xa. V UpdateRule c gn ti Cascade ,nn khi bn thay i DataColumn trong DataTable cha trong ForeignKeyConstraint c to ra, th s thay i ging nh vy cng c thc hin trong bt k i tng DataRow tng ng no trong DataTable con. Bn s hc nhiu hn v iu ny sau y trong mc " Vn sy ra khi cp nht kha chnh ca mt hng cha"
NH HNG NHNG I TNG DataRow TRONG NHNG I TNG DataTable CHA V CON
nh hng nhng i tng DataRow trong nhng i tng DataTable lin quan , bn s dng nhng phng thc GetChildRows() v GetParentRows() ca mt DataRow.
S DNG PHNG THC GetChildRow(): Bn s dng phng thc GetChildRows() ly nhng i tng DataRow con lin quan t DataRow cha. Chng hn, m sau y trnh by nhng i tng DataRow cha t DataTable customersDT v nhng i tng DataRow con lin quan ca chng t DataTable ordersDT:
DataRow[] ordersDRs = customerDR.GetChildRows("CustomersOrders"); Console.WriteLine("This customer placed the following orders:"); foreach (DataRow orderDR in ordersDRs) { Console.WriteLine("OrderID = " + orderDR["OrderID"]); } } u ra t m ny nh sau: CustomerID = ALFKI CompanyName = Alfreds Futterkiste This customer placed the following orders: OrderID = 10643 OrderID = 10692 OrderID = 10702 OrderID = 10835 OrderID = 10952 OrderID = 11011
CustomerID = ANATR CompanyName = Ana Trujillo Emparedados y helados This customer placed the following orders: OrderID = 10308 OrderID = 10625 OrderID = 10759 OrderID = 10926
S DNG PHNG THC GetParentRow(): Bn s dng phng thc GetParentRow() ly DataRow cha t DataRow con. Chng hn, m sau y hin th DataRow con u tin t ordersDT v DataRow cha lin quan ca n t customersDT:
DataRow parentCustomerDR = ordersDT.Rows[0].GetParentRow("CustomersOrders"); Console.WriteLine("\nOrder with OrderID of " + ordersDT.Rows[0]["OrderID"] + " was placed by the following customer:"); Console.WriteLine("CustomerID = " + parentCustomerDR["CustomerID"]); u ra t m ny nh sau:
Order with OrderID of 10643 was placed by the following customer: CustomerID = ALFKI
THM, CP NHT V XA NHNG HNG LIN QUAN:
Trong mc ny, bn s hc cch thc hin nhng thay i trong nhng i tng DataTable ct gi nhng hng t nhng bng Customers v Orders . Nhng bng ny c quan h thng qua kha ngoi CustomerID. Nh bn s thy, bn phi y nhng thay i ti c s d liu nm bn di theo mt trt t ch nh. Nu bn khng thc hin, chng trnh ca bn s pht sinh mt ngoi l. Ghi ch: Bn s tm thy tt c m nhng v d trnh by trong mc ny trong chng trnh ModifyingRelatedData.cs .
THIT LP NHNG I TNG DataAdapter:
Bn s cn hai i tng DataAdapter: . Mt lm vic vi bng Customers, m s c t tn customersDA. . Mt lm vic vi bng Orders, m s c t tn ordersDA. Chng ta hy xem xt vic thit lp hai i tng DataAdapter ny.
THIT LP DataAdapter customersDA: M sau y to ra v thit lp mt DataAdapter c tn customersDA cha pht biu cn thit SELECT, INSERT, UPDATE, v DELETE truy nhp bng Customers:
SqlDataAdapter customersDA = new SqlDataAdapter();
// create a SqlCommand object to hold the SELECT SqlCommand customersSelectCommand = mySqlConnection.CreateCommand(); customersSelectCommand.CommandText = "SELECT CustomerID, CompanyName " + "FROM Customers";
// create a SqlCommand object to hold the INSERT SqlCommand customersInsertCommand = mySqlConnection.CreateCommand(); customersInsertCommand.CommandText = "INSERT INTO Customers (" + " CustomerID, CompanyName " + ") VALUES (" + " @CustomerID, @CompanyName" + ")"; customersInsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); customersInsertCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
// create a SqlCommand object to hold the DELETE SqlCommand customersDeleteCommand = mySqlConnection.CreateCommand(); customersDeleteCommand.CommandText = "DELETE FROM Customers " + "WHERE CustomerID = @OldCustomerID " + "AND CompanyName = @OldCompanyName"; customersDeleteCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar, 5, "CustomerID"); customersDeleteCommand.Parameters.Add("@OldCompanyName", SqlDbType.NVarChar, 40, "CompanyName"); customersDeleteCommand.Parameters["@OldCustomerID"].SourceVersion = DataRowVersion.Original; customersDeleteCommand.Parameters["@OldCompanyName"].SourceVersion = DataRowVersion.Original;
// set the customersDA properties // to the SqlCommand objects previously created customersDA.SelectCommand = customersSelectCommand; customersDA.InsertCommand = customersInsertCommand; customersDA.UpdateCommand = customersUpdateCommand; customersDA.DeleteCommand = customersDeleteCommand;
Ch rng pht biu UPDATE ch sa i gi tr ct CompanyName; n khng sa i gi tr ct kha chnh CustomerID. Bn s hc v nhng vn lin quan vi vic cp nht mt gi tr ct kha chnh sau trong mc " Nhng vn lin quan khi cp nht kha chnh ca mt hng cha ." Chng trnh ModifyingRelatedData.cs cha mt phng thc c tn SetupCustomersDA() thc hin m trc y.
THIT LP DataAdapter ordersDA:
M sau y to ra v thit lp mt i tng DataAdapter c tn ordersDA cha nhng pht biu cn thit SELECT, INSERT, UPDATE, v DELETE truy nhp bng Orders; ch ordersInsertCommand cha c hai gm mt pht biu INSERT v mt pht biu SELECT truy xut ct OrderID mi, ct ny l mt ct kha chnh c mt gi tr c t ng sinh ra bi c s d liu
SqlDataAdapter ordersDA = new SqlDataAdapter();
// create a SqlCommand object to hold the SELECT SqlCommand ordersSelectCommand = mySqlConnection.CreateCommand(); ordersSelectCommand.CommandText = "SELECT OrderID, CustomerID, ShipCountry " + "FROM Orders";
// set the ordersDA properties // to the SqlCommand objects previously created ordersDA.SelectCommand = ordersSelectCommand; ordersDA.InsertCommand = ordersInsertCommand; ordersDA.UpdateCommand = ordersUpdateCommand; ordersDA.DeleteCommand = ordersDeleteCommand;
Chng trnh ModifyingRelatedData.cs cha mt phng thc c tn SetupOrdersDA() thc hin m trc y.
TO V C TR MT Dataset: Tip theo, v d sau to ra v c tr mt Dataset t tn myDataSet vi nhng hng t nhng bng Customers v Orders s dng customersDA V ordersDA:
Bi v DataColumn OrderID ca ordersDT c thit lp nh mt kha chnh, n s t ng c gn gi tr ban u l -1. Khi DataRow ny c y ti c s d liu, pht biu SELECT trong ordersDA s gn OrderID ti gi tr duy nht c pht sinh bi c s d liu cho hng mi trong bng Orders. Bn s thy cch y nhng s thay i ti c s d liu khng lu na trong mc "y nhng s thay i customersDT v ordersDT ti C s d liu." Chng trnh ModifyingRelatedData.cs thc hin m trc y trong phng thc Main().
CP NHT NHNG I TNG DataRow T customersDT V ordersDT:
V d sau y cp nht CompanyName customerDR ti Widgets Inc.:
customerDR["CompanyName"] = "Widgets Inc.";
V d k tip cp nht ShipCountry orderDR ti USA
orderDR["ShipCountry"] = "USA";
Chng trnh ModifyingRelatedData.cs thc hin m trc y trong phng thc Main().
XA NHNG I TNG DataRow T customersDT V ordersDT:
V d sau y xa DataRow customerDR t customersDT DataTable:
customerDR.Delete();
Trc trong mc "Kho st nhng s rng buc c to ra bi DataRelation," bn thy mt ForeignKeyConstraint c thm vo DataTable con theo mc nh khi mt i tng DataRelation c thm vo mt Dataset. Bn cng nhn thy thuc tnh DeleteRule ca i tng ForeignKeyConstraint c gn l Cascade theo mc nh. iu ny c ngha l khi DataRow trong DataTable cha b xa, do nhng i tng DataRow tng ng trong DataTable con cng b xa. Bi vy, trong v d trc y, khi customerDR b xa t customersDT, cng tng t nh orderDR trong ordersDT. Chng trnh ModifyingRelatedData.cs thc hin m trc y trong phng thc Main().
Y NHNG THAY I TRONG customersDT V ordresDT TI C S D LIU:
Trong mc ny, bn s hc cch y nhng thay i lm trc trong nhng i tng DataTable : customersDT v ordersDT ti c s d liu. Khi y nhng s thay i ti c s d liu bn phi p dng chng trong mt trt t tha mn nhng s rng buc kha ngoi trong nhng bng lin quan.
Chng hn, mt hng trong bng Customers vi mt CustomerID l J6COM phi tn ti trc khi mt hng vi CustomerID c th c thm vo bng Orders. Tng t, bn khng th xa hng c mt CustomerID l J6COM trong khi c nhng hng vi CustomerID ny trong bng Orders. Cui cng, tt nhin, bn ch c th cp nht nhng hng tn ti trong mt bng.
i theo nhng bc ny khi y nhng s thay i t customersDT v ordersDT n c s d liu: 1. y nhng i tng DataRow c thm vo customersDT ti bng Customers. 2. y nhng i tng DataRow c thm vo ordersDT ti bng Orders. 3. y nhng i tng DataRow c cp nht customersDT ti bng Customers. 4. y nhng i tng DataRow c cp nht ordersDT ti bng Orders. 5. Xa nhng i tng DataRow c loi b t ordersDT t bng Orders. 6. Xa nhng i tng DataRow c loi b t customersDT t bng Customers.
ly nhng i tng DataRow c thm, c cp nht, hay b xa, bn s dng phng thc Select() ca mt DataTable. Phng thc Select() c ni qua trong chng trc y, v mt trong s nhng phin bn qu ti ca phng thc ny:
Vi: . filterExpression : ch nh nhng hng chn. . sortExpression : ch nh nhng hng c la chn s c sp xp nh th no. . myDataViewRowState : ch r trng thi ca nhng hng chn. Bn c th thy nhng thnh vin ca lp lit k DataViewRowState trong.Bng 11.8 trong chng trc y.
ly nhng i tng DataRow c thm vo DataTable customersDT , Bn c th s dng m sau y gi phng thc Select() :
Ch s s dng hng s Added t lit k DataViewRowState.iu ny cho bit ch nhng i tng DataRow mi b sung customersDT s c tr li v lu tr trong newCustomersDRArray. V ri bn c th y nhng i tng DataRow trong newCustomersDRArray ti bng Customers trong c s d liu s dng lnh gi sau y ti phng thc Update() ca DataAdapter customersDA:
int numOfRows = customersDA.Update(newCustomersDRArray);
Gi tr Int : numOfRows l s lng hng c thm vo bng Customers. M sau y s dng su bc c trnh by trc y tt c nhng s thay i ti c s d liu; ch nhng hng s khc nhau c dng t b m DataViewRowState ly nhng i tng DataRow c yu cu .
mySqlConnection.Open();
// push the new rows in customersDT to the database Console.WriteLine("Pushing new rows in customersDT to database"); DataRow[] newCustomersDRArray = customersDT.Select("", "", DataViewRowState.Added); int numOfRows = customersDA.Update(newCustomersDRArray); Console.WriteLine("numOfRows = " + numOfRows);
// push the new rows in ordersDT to the database Console.WriteLine("Pushing new rows in ordersDT to database"); DataRow[] newOrdersDRArray = ordersDT.Select("", "", DataViewRowState.Added); numOfRows = ordersDA.Update(newOrdersDRArray); Console.WriteLine("numOfRows = "+ numOfRows);
// push the modified rows in customersDT to the database Console.WriteLine("Pushing modified rows in customersDT to database"); DataRow[] modifiedCustomersDRArray = customersDT.Select("", "", DataViewRowState.ModifiedCurrent); numOfRows = customersDA.Update(modifiedCustomersDRArray); Console.WriteLine("numOfRows = " + numOfRows);
// push the modified rows in ordersDT to the database Console.WriteLine("Pushing modified rows in ordersDT to database"); DataRow[] modifiedOrdersDRArray = ordersDT.Select("", "", DataViewRowState.ModifiedCurrent); numOfRows = ordersDA.Update(modifiedOrdersDRArray); Console.WriteLine("numOfRows = " + numOfRows); // push the deletes in ordersDT to the database Console.WriteLine("Pushing deletes in ordersDT to database"); DataRow[] deletedOrdersDRArray = ordersDT.Select("", "", DataViewRowState.Deleted); numOfRows = ordersDA.Update(deletedOrdersDRArray); Console.WriteLine("numOfRows = " + numOfRows);
// push the deletes in customersDT to the database Console.WriteLine("Pushing deletes in customersDT to database"); DataRow[] deletedCustomersDRArray = customersDT.Select("", "", DataViewRowState.Deleted); numOfRows = customersDA.Update(deletedCustomersDRArray); Console.WriteLine("numOfRows = " + numOfRows);
mySqlConnection.Close();
Chng trnh ModifyingRelatedData.cs cha mt phng php c tn PushChangesToDatabase() s dng m trc y. Mt iu bn cn ch v ModifyingRelatedData.cs l n gi PushChangesToDatabase() ngay lp tc sau khi thc hin theo nhng bc sau trong phng thc Main(). 1. Thm nhng i tng DataRow vo customersDT v ordersDT. 2. Cp nht nhng i tng DataRow mi. 3. Xa nhng i tng DataRow mi.
PushChangesToDatabase() ngay lp tc c gi sau mi buc ny do bn c th nhn thy hot ng c s d liu khi chng trnh tin trin. Ti c th n gin gi PushChangesToDatabase() mt ln ti thi im kt thc ca ba bc ny _nhng ri bn khng thy c bt k s thay i no ti c s d liu, v nhng hng mi c xa trong bc th 3 trc PushChangesToDatabase() c gi .
Mo nh: Trong nhng chng trnh ca mnh, bn thch vic thm, cp nht, v xa nhiu hng khc nhau trong nhng i tng DataTable ca bn, v v th y nhng s thay i mt ln thi im cui s hiu qu hn.
NHNG VN LIN QUAN KHI CP NHT KHA CHNH CA MT HNG CHA:
Trong mc ny, bn s hc v nhng vn lin quan khi th cp nht kha chnh trong mt DataTable cha , v sau y s cp nht ti bng c s d liu nm bn di. Nhng vn xut hin khi bng c s d liu con cha nhng hng c kha chnh bn mun thay i trong bng cha . Nhng v d trong mc ny s s dng nhng bng Customers v Orders, m c lin quan thng qua kha ngai trn ct CustomerID ca bng Orders ti ct CustomerID ca bng Customers. Nh bn s hc, tt hn nhiu bn ri b, khng cho php nhng s thay i ti ct kha chnh ca mt bng. Nu bn cho php thay i ti ct kha chnh, th nh bn s thy khng lu sau y, bn c th gp nhng vn khi y nhng thay i ti c s d liu. Thay vo , bn cn phi gn thuc tnh ReadOnly l true cho DataColumn kha chnh trong DataTable cha ca bn, v cng t ReadOnly l true cho DataColumn kha ngoi trong DataTable con ca bn. iu ngn nga nhng s thay i ti nhng gi tr trong nhng i tng DataColumn ny. Nu bn tht s cn thay i nhng gi tr kha chnh v kha ngoi, bn cn phi xa v sau ti to nhng hng trong c s d liu vi nhng gi tr kha chnh v kha ngoi mi . Bn c th iu khin cch cp nht v xa c thc hin nh th no s dng nhng thuc tnh ca kha ngoi trong c s d liu SQL Server v c nhng thuc tnh UpdateRule v DeleteRule ca mt i tng ForeignKeyConstraint na . Bn s khm ph c hai tit mc ny trong nhng mc sau y.
S L CP NHT V XA S DNG SQL SERVER:
Bn c th iu khin cch cp nht v xa c thc hin nh th no s dng SQL Server bng cch thit t nhng thuc tnh ca kha ngai . Bn thit t nhng thuc tnh ny s dng tab Relationships ca hp thoi "nhng thuc tnh ca bng c s d liu". Bn m hp thoi ny trong Enterprise Manager cho bng Orders bi thc hin nhng bc sau y:
1. Click phi bng Orders tm thy trong nhng nt bng ca Enterprise Manager. 2. La chn bng Design t danh sch s ra. 3. Click nt Manage Relationships trong thanh cng c ca hp thoi Design Table. 4. Chn kha ngoi bn mun kho st trong danh sch th xung Select relationship .
Hnh 12.1 hin th tab Relationships cho kha ngai c tn FK_Orders_Customers n cha nhng chi tit ca kha ngoi gia nhng bng Orders v Customers. Nh bn c th thy, hai bng ny c lin quan thng qua mt kha ngoi trn ct CustomerID.
Hp check box "Cascade Update Related Fields" cho bit liu c phi mt thay i ti mt gi tr trong ct kha chnh ca bng kha chnh (bng cha) cng c thc hin ti ct kha ngoi ca nhng hng tng ng ca bng kha ngoi (bng con). Chng hn, gi thit hp ny c chn v bn thay i CustomerID trong hng ca bng Customers t ALFKI n ANATR; iu ny cng gy cho ct CustomerID thay i t ALFKI n ANATR trong nhng hng ca bng Orders. Tng t, hp kim "Cascade Delete Related Records " ch nh liu vic xa mt hng trong bng kha chnh cng xa bt k hng lin quan no t bng kha ngoi . Chng hn, gi thit hp kim ny c chn v bn xa hng c CustomerID l ANTON t bng Customers; iu ny gy ra nhng hng vi CustomerID l ANTON cng b xa t bng Orders. Ghi ch: in hnh, bn cn phi c hai hp kim trong trng thi khng chn mc nh ca chng. Nu bn chn chng, c s d liu s lm thay i ti nhng hng trong bng con pha sau ng cnh v nh bn s thy khng lu sau y, bn s gp nhng vn khi y nhng s thay i t dataset ca cc bn n c s d liu.
Kim sot cp nht v xa s dng nhng thuc tnh UpdateRule v DeleteRule ca mt i tng ForeignKeyConstraint
Bn c th cng kim sot nhng s cp nht v xa s dng nhng thuc tnh UpdateRule v DeleteRule ca mt i tng ForeignKeyConstraint. Nhng thuc tnh ny thuc kiu lit k System.Data.Rule ; nhng thnh vin ca kiu ny c trnh by trong Bng 12.4.
Bng 12.4: nhng thnh vin lit k- Rule (quy tc) Hng s M t Cascade Ch nh vic xa hay cp nht ti nhng i tng DataRow trong DataTable cha cng c Hng s M t thc hin trong DataTable con. y l mc nh. None cho bit khng c hot ng no xy ra. SetDefault cho bit nhng gi tr DataColumn trong DataTable cha s c thit lp ti gi tr trong thuc tnh DefaultValue ca DataColumn. SetNull cho bit nhng gi tr DataColumn trong DataTable con s c gn ti DBNull (gi tr null)
Theo mc nh, UpdateRule c gn l cascade; bi vy, khi bn thay i DataColumn trong DataTable cha trong ForeignKeyConstraint c to ra, th s thay i ging nh vy cng c thc hin trong bt k i tng DataRow tng ng no trong DataTable con. Bn cn phi gn UpdateRule ti None trong chng trnh ca bn; ngoi ra, nh bn s hc trong mc k tip, bn s gp nhng vn khi y nhng thay i t Dataset ca bn n c s d liu. Theo mc nh, DeleteRule c gn l Cascade ; do , khi bn xa mt DataRow trong DataTable cha, th bt k i tng DataRow tng ng no trong DataTable con u cng b xa. iu ny hu ch, min l bn nh y nhng s xa ti bng con trc khi bn y nhng s xa ti bng cha.
Cp nht kha chnh ca mt Bng cha v y s thay i ti C s d liu
Trong mc ny bn s hc nhng g s xy ra nu bn th cp nht kha chnh trong mt bng cha khi c nhng hng tng ng trong bng con. Gi thit nh sau: C mt hng trong bng Customers vi mt CustomerID l J6COM. Mt bn sao ca hng ny c ct gi trong mt DataTable c tn customersDT. C mt hng trong bng Orders cng c mt CustomerID l J6COM. Mt bn sao ca hng ny c ct gi trong mt DataTable c tn ordersDT. i tng DataTable - CustomersDT v ordersDT lin h ln nhau s dng DataRelation sau y : DataRelation customersOrdersDataRel = new DataRelation( "CustomersOrders", customersDT.Columns["CustomerID"], ordersDT.Columns["CustomerID"] ); myDataSet.Relations.Add( customersOrdersDataRel );
By gi, hai s thit t cho hp kim "Cascade Update Related Fields" (ng b cp nht nhng trng quan h) cho FK_Orders_Customers l: B chn , c ngha l nhng s thay i i vi gi tr kha chnh CustomerID trong bng Customers khng c buc kt ti bng Orders. y l mc nh. Chn hp kim, c ngha l nhng s thay i i vi gi tr kha chnh CustomerID trong bng Customers c buc kt ti bng Orders. Ngoi ra, nhng s thit t v quyn hn cho thuc tnh UpdateRule ca i tng ForeignKeyConstraint c thm vo khi DataRelation trc c to ra Cascade , c ngha l nhng s thay i i vi DataColumn CustomerID ca customersDT c buc kt ti ordersDT. y l mc nh. None, ngha l nhng s thay i ti DataColumn CustomerID ca customersDT khng c buc kt ti ordersDT. Hy kho st ba trng hp quan trng nht l: thay i vic chn kim ca hp kim "Cascade Update Related Fields" v vic thit t thuc tnh UpdateRule n Cascade v sau l None. Ghi ch: Bn c th s dng chng trnh ModifyingRelatedData2.cs nh c s th ba trng hp m t trong mc ny. TRNG HP TH NHT:
Gi thit nh sau: Hp kim "Cascade Update Related Fields"c chn kim. UpdateRule c gn ti Cascade . Nu bn thay i gi tr DataColumn CustomerID t J6COM thnh J7COM v y s thay i ti c s d liu, v s thay i c thc hin cch thnh cng trong nhng i tng DataTable customersDT v ordersDT v cng trong nhng bng Customers v Orders. N lm vic tt min l bn ch s dng ct OrderID trong mnh WHERE ca i tng Command trong thuc tnh UpdateCommand ca DataAdapter ca bn. Chng hn: ordersUpdateCommand.CommandText = "UPDATE Orders " + "SET " + " CustomerID = @NewCustomerID " + "WHERE OrderID = @OldOrderID";
Cp nht ny s dng s tng tranh " ngi sau cng thng " v ch ct kha chnh OrderID c s dng trong mnh WHERE ( ct CustomerID c c b ra khi mnh WHERE ). Nh c cp trong chng trc y, s tng tranh "ngi sau cng hng " rt t bi v mt ngi s dng c th ghi ln mt s thay i c thc hin bi ngi s dng khc. Nu thay vo bn cng bao gm gi tr ct CustomerID c trong mnh WHERE ca s Cp nht, nh trnh by trong v d sau y, ordersUpdateCommand.CommandText = "UPDATE Orders " + "SET " + " CustomerID = @NewCustomerID " + "WHERE OrderID = @OldOrderID " + "AND CustomerID = @OldCustomerID";
V ri s y thay i ti c s d liu s tht bi v hng nguyn thy trong bng Orders khng c tm thy do CustomerID c thay i t J6COM thnh J7COM trong bng Orders mt cch t ng bi c s d liu do hp kim "Cascade Update Related Fields " c chn kim cho kha ngoi trong bng Orders, nhng trong ordersDT gi tr CustomerID c gn l J6COM. Bi vy, S thm ca OrderID = @OldOrderID trong mnh WHERE cn tr hng c tm thy. lnh UPDATE gy ra mt DBConcurrencyException c nm ra.
TRNG HP TH HAI:
Gi thit nh sau: Hp kim "Cascade Update Related Fields" khng c chn. UpdateRule c gn ti Cascade. Thuc tnh CommandText ca i tng Command trong thuc tnh UpdateCommand ca DataAdapter c thit t nh sau:
ordersUpdateCommand.CommandText = "UPDATE Orders " + "SET " + " CustomerID = @NewCustomerID " + "WHERE OrderID = @OldOrderID"; Nu bn thay i CustomerID t J6COM ti J7COM trong customersDT v y s thay i ti c s d liu, v s cp nht s nm mt SqlException. y l v bng con Orders hin ang cha mt hng vi CustomerID l J6COM, v bi v kha ngai bn khng th thay i CustomerID trong bng cha Customers. M d bn th thay i CustomerID trong ordersDT trc v c gng y s thay i ti c s d liu, bn s gp ngoi l ging nh vy.
TRNG HP TH BA:
Gi thit nh sau: Cascade Update Related Fields khng c kim chn. UpdateRule c gn ti None. CommandText ca i tng Command trong UpdateCommand ca DataAdapter cng ging nh trong trng hp th hai. Nhng m sau y gn UpdateRule ca ChildKeyConstraint n None :
Nu bn th thay i CustomerID t J6COM ti J7COM trong customersDT, th bn s gy ra mt InvalidConstraintException. y l v DataTable con ordersDT hin thi cha mt DataRow vi CustomerID l J6COM, v v kha ngoi bn khng th thay i CustomerID trong DataTable cha customersDT . Mc d bn th thay i CustomerID trong ordersDT trc, bn s gp ngoi l ging nh vy .
Kt lun: S cng bc ca nhng s rng buc trong ba v d trc y l ng, v chng cho thy mt s nhc u khi thay i nhng gi tr ct kha chnh c th em n. trng hp u tin l mt trng hp duy nht hat ng, v mc d bn phi s dng n s tng tranh " ngi sau cng thng " trong pht biu UPDATE, m in hnh bn cn phi trnh.
Bn s lm g nu nh bn mun thay i gi tr ct kha chnh v p dng s thay i ging nh vy ti nhng hng con ? Cch d dng nht l n gin xa nhng hng trong bng con trc, thay i gi tr kha chnh trong bng cha , v ti to nhng hng trong bng con vi gi tr kha chnh mi.
MNG LI XML:
Nh c cp trong Chng 10, " S dng nhng i tng Dataset lu tr d liu, " mt Dataset cha hai phng thc gi ra ni dung ca nhng i tng DataRow nh XML: . GetXml() tr v mt dng trnh by XML ca d liu ct gi trong Dataset nh mt chui. . WriteXml() vit d liu t i tng Dataset ra thnh mt file di dng XML. Mt DataRelation cha ng mt thuc tnh c tn Nested, t n c` th ly hay gn mt gi tr bool cho bit liu c phi nhng i tng DataRelation c kt vo. iu ny hu ch khi nh ngha nhng mi quan h c th bc trong XML.
c bit, khi bn gn Nested l true, nhng hng con s c kt vo bn trong nhng hng cha trong bt k file XML no m bn gi ra - s dng nhng phng thc GetXml() v WriteXml() . Tng t, bn c th c nhng hng c kt vo khi gi phng thc ReadXml() ca mt Dataset c mt file XML.
Thuc tnh Nested ca mt i tng DataRelation c gn ti true nh trong v d sau y:
iu ny c trnh by trong Danh sch 12.1. Ch chng trnh ny vit ra hai file XML c tn nonNestedXmlFile.xml v nestedXmlFile.xml. nonNestedXmlFile.xml cha nhng hng khng c lng vo theo mc nh, v nestedXmlFile.xml cha nhng hng c lng vo sau khi thuc tnh Nested ca i tng DataRelation c gn ti true .
Danh sch 12.1: NESTEDXML.CS /* NestedXml.cs illustrates how setting the Nested property of a DataRelation to true causes the the child rows to be nested within the parent rows in the output XML */
using System; using System.Data; using System.Data.SqlClient;
class NestedXml { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 CustomerID, CompanyName " + "FROM Customers " + "ORDER BY CustomerID;" + "SELECT OrderID, CustomerID, ShipCountry " + "FROM Orders " + "WHERE CustomerID IN (" + " SELECT TOP 2 CustomerID " + " FROM Customers " + " ORDER BY CustomerID " + ")"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Table"]; DataTable ordersDT = myDataSet.Tables["Table1"];
// create a DataRelation object named customersOrdersDataRel DataRelation customersOrdersDataRel = new DataRelation( "CustomersOrders", customersDT.Columns["CustomerID"], ordersDT.Columns["CustomerID"] ); myDataSet.Relations.Add( customersOrdersDataRel );
// write the XML out to a file Console.WriteLine("Writing XML out to file nonNestedXmlFile.xml"); myDataSet.WriteXml("nonNestedXmlFile.xml");
// set the DataRelation object's Nested property to true // (causes child rows to be nested in the parent rows of the // XML output) myDataSet.Relations["CustomersOrders"].Nested = true;
// write the XML out again (this time the child rows are nested // within the parent rows) Console.WriteLine("Writing XML out to file nestedXmlFile.xml"); myDataSet.WriteXml("nestedXmlFile.xml"); } }
Danh sch 12.2 hin th file nonNestedXmlFile.xml c xut ra bi chng trnh. Ch nhng hng cha t bng Customers c lit k u tin, theo sau l nhng hng con t bng Orders. Nhng hng con khng c lng bn trong nhng hng cha .
NH NGHA MT MI QUAN H S DNG Visual Studio .NET Trong mc ny, bn s thy cch to ra mt ng dng Windows trong Visual Studio .NET (VS .NET) vi mt Dataset cha hai i tng DataTable nh th no . Nhng i tng DataTable ny s tham chiu nhng bng Customers v Orders trong c s d liu . Bn s hc cch nh ngha mt mi quan h gia nhng hai i tng DataTable trong m hnh XML nh th no.
TO MT TRNH NG DNG WINDOWS:
Thc hin nhng bc sau y to ng dng Windows: 1. M VS .NET v chn File New Project v to ra mt ng dng Windows mi . Nhp tn ca d n l DataRelation, nh trnh by trong Hnh 12.2.
2. Kch nt Ok tip tc. 3. M Server Explorer v kt ni ti c s d liu Northwind - s dng kt ni bn dng trong nhng chng trc y. Bn c th m Server Explorer bi chn View Server Explorer. M rng nhng nt bng trong cy th mc v chn c hai bng Customers v Orders bng cch nhn Ctrl + kch nt tri chn cc bng, nh trnh by trong Hnh 12.3.
4. Ko nhng bng Customers v Orders ti form ca bn. VS .NET s t ng to ra ba i tng trong khay bn di form ca bn. Nhng i tng ny c tn sqlConnection1 (dng truy cp c s d liu Northwind) sqlDataAdapter1 (dng x l truy cp ti bng Cudtomers), v sqlDataAdapter2 (dng x l s truy cp ti bng Orders). Nhng i tng ny c trnh by trong Hnh 12.4.
5. Tip theo, bn cn mt i tng Dataset cha nhng i tng DataTable lu tr nhng hng t nhng bng Customres v Orders. to ra mt i tng Dataset, kch vo khong trng trn form ca bn v sau kch vo lin kt Generate Dataset y ca ca s Properties thuc form trnh by trong hnh Hnh 12.4 trc.
iu ny lm hin th hp thoi "Generate Dataset" , nh trong Hnh 12.5. nguyn tt c nhng s thit t trong hi thoi ny trong trng thi mc nh ca chng.
Ch mt Dataset mi s c to ra, v nhng bng Customers v Orders c s dng trong Dataset mi. Dataset mi s cng c thm vo b thit k, nh c ch nh bi hp kim trong hp thoi. Kch nt Ok tip tc. Mt Dataset mi c tn dataSet11 s c thm vo khay bn di form ca bn.
Thm mt quan h vo m hnh XML ca Dataset
Thc hin nhng bc sau y thm mt quan h vo m hnh XML ca Dataset ca bn: 1. Chn Dataset mi ca bn trong khay v kch lin kt "View Schema" trong ca s nhng thuc tnh. vic ny hin th ca s "Schema Editor" (b bin tp m hnh), nh trong Hnh 12.6.
Ko mt relation t tab "XML Schema" trong Toolbox n thc th bng Orders. Vic ny m hp thoi "Edit Relation " (Son tho quan h) , nh trong Hnh 12.7.
Nh bn c th thy t Hnh 12.7, bn c th gn quan h cng vi nhng chi tit khc cho nhng bng cha v con , kha chnh v kha ngoi .
3. nguyn nhng s thit t trong hp thoi Edit Relation trong trng thi mc nh ca chng v kch nt Ok tip tc.
Vic ny thm quan h mi vo nhng thc th Customers v Oerders trong m hnh XML. Bn c th kch vo biu tng "kim cng" gia nhng thc th Customers v Ordres xem nhng thuc tnh ca quan h, nh trnh by trong Hnh 12.8.
Ghi ch Bn c th thm mt quan h vo mt Dataset nh kiu mnh trong cng cch vi mc c m t trong phn ny.
Tm lc Trong chng ny, bn i su vo nhng chi tit ca nhng i tng UniqueConstraint v ForeignKeyConstraint. Bn cng hc cch nh ngha mt mi quan h gia nhng i tng DataTable s dng mt i tng DataRelation nh th no, i tng quan h ny theo mc nh t ng to ra mt nhng i tng UniqueConstraint v ForeignKeyConstraint cho Bn. i tng UniqueConstraint c thm vo DataTable cha ca bn v ForeignKeyConstraint c thm vo DataTable con ca bn. Bn cng thy cch nh hng nhng hng trong nhng i tng DataTable lin quan nh th no, thc hin nhng s thay i trong nhng i tng DataTable lin quan , v cui cng y nhng s thay i ti c s d liu. Trong chng k tip, bn s hc cch s dng nhng i tng DataView nh th no .
CHNG 13: S DNG NHNG I TNG DataView: Tng quan Trong chng 11, "S dng nhng i tng Dataset sa i D liu, " Bn thy bn c th lc v phn loi nhng i tng DataRow mt DataTable s dng phng thc Select() . Trong chng ny, bn s hc s dng nhng i tng DataView cng lc v phn loi nhng hng. Li th ca mt DataView l bn c th kt buc n ti mt thnh phn trc quan nh mt iu khin DataGrid, v bn s cng s thy cch lm iu trong chng ny. Mt DataView lu tr nhng bn sao ca nhng hng trong mt DataTable nh nhng i tng DataRowView. Nhng i tng DataRowView cung cp s truy cp ti nhng i tng DataRow nm bn di trong mt DataTable. Bi vy, khi bn kho st v sa i ni dung ca mt DataRowView, Bn tht s ang lm vic vi DataRow nm bn di. hy nh iu ny khi c chng ny. Ch im trong chng ny: . Lp DataView . To ra v s dng mt i tng DataView . S dng gii thut phn loi mc nh . Thc hin s lc nng cao . Lp DataRowView . Tm nhng i tng DataRowView trong mt DataView . Thm, iu chnh, v loi b nhng i tng DataRowView t mt DataView . To nhng i tng DataView con . Lp DataViewManager . To ra v s dng mt i tng DataViewManager . Vic to mt DataView s dng Visual Studio .NET
LP DATAVIEW: Bn s dng mt i tng ca lp DataView xem ch nhng hng c bit trong mt i tng DataTable s dng mt b lc. Bn cng c th phn loi nhng hng c xem bi mt DataView. Bn c th thm, sa i, v loi b nhng hng t mt DataView, v nhng s thay i s cng c ng dng vo DataTable nm bn di m DataView c c; bn s hc nhiu hn v iu ny sau trong mc "Thm, iu chnh, v loi b nhng i tng DataRowView t mt DataView." Bng 13.1 cho thy mt s nhng thuc tnh DataView, v bng 13.2 cho thy mt s nhng phng thc DataView. Bng 13.1: nhng thuc tnh DataView Thuc tnh Kiu d liu M t AllowDelete bool Ly hay gn mt gi tr bool cho bit liu c phi s xa ca nhng i tng DataRowView t DataView ca bn c cho php. Mc nh l true. AllowEdit bool Ly hay gn mt gi tr bool cho bit liu c phi s sa i ca nhng i tng DataRowView trong DataView ca bn c cho php. Mc nh l true. AllowNew bool Ly hay gn mt gi tr bool cho bit liu c phi vic thm nhng i tng DataRowView mi vo DataView ca bn c cho php. Mc nh l true. ApplyDefaultSort bool Ly hay gn mt gi tr bool cho bit liu c phi s dng gii thut phn loi mc nh phn loi nhng hng trong DataView ca bn. Khi gn l true, phn loi mc nh c s dng v c gn ti "th t tng dn" ca thuc tnh PrimaryKey ca DataTable nm bn di (nu PrimaryKey c thit t). Mc nh l false. Count int Ly s lng hng hin th i vi DataView ca bn. DataViewManager DataViewManager Ly DataViewManager c lin h vi DataView ca bn. Bn s hc v nhng i tng DataViewManager sau trong mc "To v s dng mt i tng DataViewManager." RowFilter string Ly hay gn biu thc c dng lc nhng hng trong DataView ca bn. RowStateFilter DataViewRowState Ly hay gn biu thc c dng lc nhng hng da vo nhng hng s t lit k DataViewRowState. Nhng gi tr c trnh by trong Bng 13.3. Sort string Ly hay gn mt biu thc cho bit nhng ct cn phn loi bi mt trt t sp xp v ty chn cho nhng hng trong DataView ca bn. Biu thc chui ny cha tn ct theo sau l ASC (sp xp tng) hay DESC (sp xp gim). Mt ct c sp xp tng dn theo mc nh. Bn phn chia nhiu ct bng nhng du phy trong chui. V d: CustomerID ASC, CompanyName DESC. Table DataTable Ly hay gn DataTable nm bn di m DataView ca bn lin h n. Bng 13.2: nhng phng thc ca DataView Phng thc Kiu tr v M t AddNew() DataViewRow Thm mt DataRowView mi vo DataView ca bn, v do thm mt DataRow mi vo DataTable nm bn di. BeginInit() void Bt u s khi to runtime ca DataView ca bn trong mt form hay thnh phn. CopyTo() void Sao chp nhng hng t DataView ca bn vo trong mt mng. Phng thc ny ch dnh cho nhng giao din Web form. Delete() void Xa DataRowView c ch s c ch nh ra khi DataView ca bn. S xa ca DataRow nm bn di khng c duy tr cho n khi bn gi phng thc AcceptChanges() ca DataTable ca bn. Bn c th hu lnh xa bng cch gi phng thc RejectChanges() ca DataTable ca bn. EndInit() void Kt thc s khi to runtime ca DataView ca bn trong mt form hay thnh phn. Find() int B qu ti. Tm v tr v ch s ca DataRowView vi kha chnh c ch r trong DataView ca bn. Gi tr Int c tr li bi phng thc ny l ch s ca DataRowView nu c tm thy; nu khng -1 c tr v. trc tin bn phi t thuc tnh Sort ca DataView ca bn phn lai trn kha chnh. Chng hn, nu bn mun tm mt DataRowView t c s trn CustomerID, Bn phi t Sort ti CustomerID, CustomerID ASC, hay CustomerID DESC. FindRows() DataRowView[] B qu ti. Tm v tr li mt mng ca nhng i tng DataRowView c nhng ct thch ng vi kha chnh ch nh. Nh vi phng thc Find() , bn phi gn thuc tnh Sort ca DataView ca bn cho kha chnh trc khi gi phng thc FindRows() . Bng 13.2: nhng phng thc ca DataView Phng thc Kiu tr v M t GetEnumerator() IEnumerator Tr li mt b m cho DataView ca bn. ToString() string Tr li mt chui i din cho DataView ca bn. Bng 13.3: nhng thnh vin Lit k DataViewRowState
HNG S M T Added Mt hng mi thm CurrentRows Nhng hng hin thi, bao gm khng thay i, hng c thm, v nhng hng sa i. Deleted mt hng b xa ModifiedCurrent mt hng c sa i ModifiedOriginal hng nguyn thy trc khi sa i None Khng ph hp vi bt k hng no trong DataTable. OriginalRows Nhng hng nguyn bn, bao gm nhng hng khng thay i v b xa . Unchanged Mt hng m khng b sa i.
Mt trong s nhng s kin DataView l ListChanged. N pht khi khi danh sch c qun l bi DataView ca bn thay i. B x l s kin ca n l ListChangedEventHandler. Bng 13.3 cho thy nhng thnh vin lit k ca System.Data.DataViewRowState . S lit k ny c s dng vi thuc tnh RowState ca mt DataTable; thuc tnh ny c dng ch r nhng hng c xem bi DataView c lc bi DataViewRowState ca chng.
TO V S DNG MT I TNG DATAVIEW:
Trong mc ny, bn s hc cch lc v phn loi nhng hng nh th no vi mt i tng DataView. Bn to ra mt i tng DataView s dng mt trong s nhng b khi dng sau y :
. myDataTable ch nh DataTable m DataView ca bn lin h n. DataView ca n s c nhng hng t DataTable ny. Thuc tnh Table ca DataView ca bn c gn ti myDataTable. . filterExpression ch nh mt chui cha biu thc bn mun dng lc nhng hng . Thuc tnh RowFilter ca DataView ca bn gn ti filterExpression. . sortExpression ch nh mt chui cha biu thc bn mun dng phn loi nhng hng . Thuc tnh Sort ca DataView ca bn c gn ti sortExpression. . rowState ch nh mt b lc b sung ng dng vo nhng hng; V d sau y to ra v c tr mt DataTable c tn customersDT cha nhng hng t bng Customers: Trc khi bn to ra mt DataView,trc tin bn cn mt DataTable t c nhng hng. V d sau y to ra v c tr mt DataTable c tn customersDT cha nhng hng t bng Customers:
Chng ta hy cho l bn mun lc nhng hng CustomersDT xem ch nhng khch hng trong UK. Biu thc chui lc ca cc s l
string filterExpression = "Country = 'UK'"; Ghi ch: Sp xp ASC : th t tng dn. sp xp DESC theo th t gim dn. Cui cng, chng ta hy cho l bn ch mun xem nhng hng nguyn bn trong DataView; do bn gn b lc trng thi hng ca bn ti DataViewRowState.OriginalRows:
DataViewRowState rowStateFilter = DataViewRowState.OriginalRows; Ghi ch: Theo mc nh l DataViewRowState.CurrentRows, bao gm nhng hng trong DataView ca bn m DataViewRowState l khng thay i, c thm vo, v ang c sa i. V d sau y to ra mt i tng DataView c tn customersDV v chuyn customersDT, filterExpression, sortExpression, v rowStateFilter n b khi dng DataView:
DataView customersDV = new DataView( customersDT, filterExpression, sortExpression, rowStateFilter ); You can also create a DataView and set the Table, RowFilter, Sort, and RowStateFilter properties individually. For example: DataView customersDV = new DataView(); customersDV.Table = customersDT; customersDV.RowFilter = filterExpression; customersDV.Sort = sortExpression; customersDV.RowStateFilter = rowStateFilter;
Mt DataView ct gi nhng hng nh nhng i tng DataRowView, v nhng hng c c t nhng i tng DataRow c ct gi trong DataTable nm bn di. V d sau y s dng mt vng foreach hi th nhng i tng DataRowView trong DataView customersDV :
foreach (DataRowView myDataRowView in customersDV) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); }
Ghi nh rng myDataRowView[count] tr v gi tr s ch v tr ca ct c ch r bi b m. Chng hn, myDataRowView[0] Tr li gi tr ca ch v tr ct CustomerID. Bn s hc nhiu hn v lp DataRowView sau trong mc "Lp DataRowView."
Lit k 13.1 trnh by mt chng trnh s dng nhng v d m trc y.
Danh sch 13.1: USINGDATAVIEW.CS /* UsingDataView.cs illustrates the use of a DataView object to filter and sort rows */
using System; using System.Data; using System.Data.SqlClient;
class UsingDataView { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Customers"]; // set up the filter and sort expressions string filterExpression = "Country = 'UK'"; string sortExpression = "CustomerID ASC, CompanyName DESC"; DataViewRowState rowStateFilter = DataViewRowState.OriginalRows;
// create a DataView object named customersDV DataView customersDV = new DataView(); customersDV.Table = customersDT; customersDV.RowFilter = filterExpression; customersDV.Sort = sortExpression; customersDV.RowStateFilter = rowStateFilter;
// display the rows in the customersDV DataView object foreach (DataRowView myDataRowView in customersDV) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); } } }
Ch rng nhng hng trong customersDV c lc vi Country l UK, v nhng hng kt qu s c sp xp theo CustomerID. u ra chng trnh ny nh sau:
AROUT Around the Horn UK
BSBEV B's Beverages UK
CONSH Consolidated Holdings UK
EASTC Eastern Connection UK
ISLAT Island Trading UK NORTS North/South UK
SEVES Seven Seas Imports UK
S dng gii thut sp xp mc nh
Nu bn mun phn nhm nhng i tng DataRowView trong DataView ca bn da vo kha chnh DataTable ca bn , Bn c th s dng mt phm tt. Thay v gn thuc tnh Sort ca DataView ca bn , Bn gn thuc tnh PrimaryKey ca DataTable v sau gn thuc tnh ApplyDefaultSort ca DataView ca bn ti true.
Thuc tnh Sort ca DataView ca bn ri s t ng c gn ti kha chnh ca DataTable ca bn. iu ny gy ra nhng i tng DataRowView trong DataView ca bn s c sp xp trong th t tng dn da vo gi tr ct kha chnh . Chng ta hy xem xt mt v d. b m sau y gn nhng thuc tnh PrimaryKey ca DataTable - customersDT ti DataColumn - CustomerID :
customersDT.PrimaryKey = new DataColumn[] { customersDT.Columns["CustomerID"] };
V d k tip t thuc tnh ApplyDefaultSort ca customersDV ti true :
customersDV.ApplyDefaultSort = true;
Thuc tnh Sort ca customersDV ri c gn ti CustomerID, n gy ra nhng i tng DataRowView s c sp xp theo gi tr tng dn ca CustomerID. Ghi ch Bn s tm thy nhng v d m trong mc ny trong chng trnh UsingDefaultSort.cs . Danh sch b b qua trong sch ny cho ngn gn.
Thc hin s lc nng cao:
Thuc tnh RowFilter ca mt DataView tng t vi mnh WHERE trong mt s pht biu SELECT. Do bn c th s dng nhng biu thc lc rt mnh trong DataView ca bn. V d, bn c th s dng nhng chc nng tng th AND, OR, NOT, IN, LIKE, nhng ton t so snh , nhng ton t s hc, nhng k t i din ( * v % ) .
Ghi ch : Chi tit v cch s dng nhng biu thc b lc nh vy trong nhng i tng DataView ca bn , tham chiu ti thuc tnh DataColumn.Expression trong ti liu trc tuyn .NET.
y l mt v d n gin s dng tan t LIKE v k t i din (%) phn trm lc nhng hng vi CustomerName bt u vi Fr:
string filterExpression = "CompanyName LIKE 'Fr%'"; customersDV.RowFilter = filterExpression;
Ch : chui Fr % c t trong nhng li trch dn n- m bn phi lm cho tt c cc k t chui. Khi m ny thay th m hin hu trong chng trnh UsingDataView.cs c trnh by trc trong Danh sch 13.1, u ra nh sau:
FRANK Frankenversand Germany
FRANR France restauration France
FRANS Franchi S.p.A. Italy
Ghi nh : ti c thc hin s thay i ny trong chng trnh UsingDataView2.cs ( Danh sch c b qua trong sch ny cho ngn gn). hy thoi mi t do kho st v chy chng trnh ny
LP DATAROWVIEW:
Nhng hng trong mt i tng DataView c ct gi nh nhng i tng ca lp DataRowView. Mt i tng DataRowView cung cp s truy cp i tng DataRow nm bn di trong DataTable. Khi bn kho st v son tho ni dung ca mt DataRowView, Bn tht s ang lm vic vi DataRow nm bn di. Bn phi nh n iu ny khi lm vic vi nhng i tng DataRowView. Bng 13.4 cho thy mt s nhng thuc tnh DataRowView, v Bng 13.5 cho thy mt s nhng phng php DataRowView.
Bng 13.4: nhng thuc tnh DataRowView
Thuc tnh Kiu d liu M t DataView DataView Ly DataView m DataRowView thuc v. IsEdit bool ly mt gi tr bool cho bit liu DataRowView ( V do DataRow nm bn di) ang trong ch son tho. IsNew bool Ly mt gi tr bool cho bit liu c phi DataRowView va mi c thm vo. Row DataRow Ly DataRow nm bn di m ang c xem t DataTable. RowVersion DataRowVersion
Ly DataRowVersion ca DataRow nm bn di . Nhng thnh vin.ca lit k System.Data.DataRowVersion l: Current : ch DataRow cha nhng gi tr hin thi. Default: ch DataRow cha nhng gi tr mc nh. Original: ch DataRow cha nhng gi tr nguyn bn. Proposed: ch DataRow cha nhng gi tr d nh.
Bng 13.5: nhng phng thc ca DataRowView
Phng thc Kiu tr v M t BeginEdit() void Bt u s son tho ca DataRowView trong DataView ca bn, V do cng bt u s son tho ca DataRow bn di trong DataTable ca bn. Ri Bn son tho DataRow ny thng qua DataRowView. CancelEdit() void hy b s son tho ca DataRowView trong DataView ca bn, V bi vy cng hy b son tho ca DataRow nm bn di trong c s d liu. CreateChildView() DataView B qu ti. tr v mt DataView cho DataTable con, nu c. Delete() void Xa DataRowView trong DataView ca bn. S xa ca DataRow nm bn di khng c giao ph trong DataTable cho n khi bn gi phng thc AcceptChanges() ca DataTable ca bn. Bn c th hu b s xa bi gi phng thc RejectChanges() ca DataTable ca bn, v cng hu bt k s thm khng giao ph hay nhng s sa i no. EndEdit() void Kt thc s son tho ca mt DataRowView.
S TM KIM NHNG I TNG DataRowView TRONG DataView:
Bn c th tm ch s ca mt DataRowView trong mt DataView s dng phng thc Find() ca mt DataView. Bn cng c th ly mt mng ca nhng i tng DataRowView s dng phng thc FindRows() ca mt DataView. Bn s hc cch s dng s nhng phng thc Find() v FindRows() trong mc ny.
TM CH S CA MT DataRowView S DNG PHNG THC Find():
Phng thc tm kim tr li ch s ca DataRowView vi kha chnh c ch r trong DataView ca bn.gi tr Int c tr li bi phng thc ny l ch s ca DataRowView nu c tm thy; nu khng -1 c tr v.
tm thy ch s ng, u tin bn phi t thuc tnh Sort ca DataView ca bn ti Sort trn kha chnh. Chng hn, nu bn mun tm mt DataRowView t c s trn CustomerID, Bn phi t thuc tnh Sort ca DataView ca bn ti CustomerID, CustomerID ASC, hay CustomerID DESC:
Gi thit rng nhng i tng DataRowView c lc trong customersDV nh sau:
AROUT Around the Horn UK
BSBEV B's Beverages UK
CONSH Consolidated Holdings UK
EASTC Eastern Connection UK
ISLAT Island Trading UK
NORTS North/South UK
SEVES Seven Seas Imports UK
V d sau y gi phng php Find() tm ch s ca DataRowView trong customersDV vi mt CustomerID l BSBEV:
int index = customersDV.Find("BSBEV");
Bi v BSBEV xut hin ti v tr c ch s 1, phng thc Find() tr li 1.
Ghi ch: Nhng i tng DataRowView trong mt DataView khi u ti ch s 0. Bi vy, BSBEV xut hin ti ch s 1.
Tm nhng i tng DataRowView s dng phng thc FindRows():
Phng thc FindRows() ca mt DataView tm v tr li mt mng ca nhng i tng DataRowView m c ct kha chnh ph hp vi kha chnh trong DataView ca bn. Nu khng c hng no c tm thy, th mng tr v s khng c phn t no, v thuc tnh Length (chiu di) ca mng s l 0.
tm nhng i tng DataRowView s dng phng thc FindRows(), u tin bn phi t thuc tnh Sort ca DataView ca bn l lc trn kha chnh. Chng hn, nu bn mun tm nhng i tng DataRowView t c s trn CustomerID, Bn phi t thuc tnh Sort ca DataView ca bn l CustomerID, CustomerID ASC, hay CustomerID DESC:
V ch c mt i tng ph hp, mng customersDRVs s cha ng mt DataRowView.
Danh sch 13.2 trnh by mt chng trnh s dng nhng phng thc Find() V FindRows()
Danh sch 13.2: FINDINGDATAROWVIEWS.CS
/* FindingDataRowViews.cs illustrates the use of the Find() and FindRows() methods of a DataView to find DataRowView objects */
using System; using System.Data; using System.Data.SqlClient;
class FindingDataRowViews { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Customers"];
// set up the filter and sort expressions string filterExpression = "Country = 'UK'"; string sortExpression = "CustomerID"; DataViewRowState rowStateFilter = DataViewRowState.OriginalRows;
// create a DataView object named customersDV DataView customersDV = new DataView(); customersDV.Table = customersDT; customersDV.RowFilter = filterExpression; customersDV.Sort = sortExpression; customersDV.RowStateFilter = rowStateFilter;
// display the rows in the customersDV DataView object foreach (DataRowView myDataRowView in customersDV) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); }
// use the Find() method of customersDV to find the index of // the DataRowView whose CustomerID is BSBEV int index = customersDV.Find("BSBEV"); Console.WriteLine("BSBEV found at index " + index + "\n");
// use the FindRows() method of customersDV to find the DataRowView // whose CustomerID is BSBEV DataRowView[] customersDRVs = customersDV.FindRows("BSBEV"); foreach (DataRowView myDataRowView in customersDRVs) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); } } }
Mo nh: Nu bn ang s dng mt phin bn trc ca NET. SDK, Bn c l gp li bin dch sau y khi bin dch chng trnh ny FindingDataRowViews .cs(59, 35): li CS0117: 'System.Data.DataView' khng cha cha mt nh ngha cho FindRows'
Nu bn gp li ny, bin tp chng trnh vi Visual Studio .NET
u ra t chng trnh ny nh sau: AROUT Around the Horn UK
BSBEV B's Beverages UK
CONSH Consolidated Holdings UK
EASTC Eastern Connection UK
ISLAT Island Trading UK
NORTS North/South UK
SEVES Seven Seas Imports UK
BSBEV found at index 1 BSBEV B's Beverages UK
THM, SA I, LOI B NHNG I TNG DataRowView T MT DataView:
S l quan trng khi bit nhng i tng DataRowView trong mt DataView cung cp nhng s truy cp ti i tng DataRow nm bn di trong mt DataTable. Bi vy, khi bn kho st v son tho ni dung ca mt DataRowView, Bn tht s ang lm vic vi DataRow nm bn di. Tng t, khi bn loi b mt DataRowView, tc bn ang loi b DataRow nm bn di.
THM MT DataRowView VO MT DataView:
thm mt DataRowView mi vo mt DataView, Bn gi phng thc AddNew() ca DataView ca bn. Phng thc AddNew() tr v mt i tng DataRowView m bn gn nhng gi tr ct cho hng mi. V d sau y gi phng thc AddNew() ca DataView customersDV:
Ch s s dng ca phng thc EndEdit() ca DataRowView customerDRV kt thc s son tho. phng thc EndEdit() to ra mt DataRow mi trong DataTable nm bn di. Nhng i tng DataColumn trong DataRow mi s cha nhng gi tr ct c ch r trong m trc y.
Ghi nh Bn c th hu b s thm bi gi phng thc CancelEdit() ca mt DataRowView.
Bn c th ly DataRow nm bn di c thm vo DataTable s dng thuc tnh Row ca mt DataRowView. Chng hn:
DataRow customerDR = customerDRV.Row;
Sa i mt DataRowView hin hu:
bt u sa i mt DataRowView hin hu trong mt DataView, Bn gi phng thc BeginEdit() ca DataRowView trong DataView ca bn. V d sau y gi phng thc BeginEdit() cho DataRowView u tin trong customersDV:
customersDV[0].BeginEdit();
Ghi ch: Nh rng nhng i tng DataRowView trong mt DataView bt u ti ch s 0, v bi vy customersDV[0] l DataRowView u tin trong customersDV.
V ri Bn c th sa i mt DataColumn trong DataRow nm bn di thng qua DataRowView.
V d sau y t DataColumn CompanyName l Widgets Inc.:
customersDV[0]["CompanyName"] = "Widgets Inc.";
Mt khi bn thc hin xong nhng sa i ca bn, bn gi phng thc EndEdit() lm cho nhng s sa i ca bn bn vng trong DataTable nm bn di. Chng hn:
customersDV[0].EndEdit();
Ghi nh: Bn c th hu b s sa i bi gi phng thc CancelEdit() ca mt DataRowView.
Loi b mt DataRowView hin hu
loi b mt DataRowView hin hu t mt DataView, Bn c th gi phng thc Delete() ca DataView hoc DataRowView. Khi gi phng thc Delete() ca mt DataView, Bn thng qua ch s ca DataRowView m bn mun loi b. V d sau y loi b DataRowView th hai t customersDV:
customersDV.Delete(1);
Khi gi phng thc Delete() ca mt DataRowView, Bn n gin gi phng thc ny ca DataRowView trong DataView ca bn. v d sau y loi b DataRowView th ba t customersDV:
customersDV[2].Delete();
Vi bt k trong ba phng thc Delete() ny, s xa khng c giao ph trong DataTable nm bn di cho n khi bn gi phng thc AcceptChanges() ca DataTable ca bn. Chng hn:
customersDT.AcceptChanges();
Ghi ch: Bn c th gi phng thc RejectChanges() ca mt DataTable hu b nhng s xa. Phng thc ny s cng hu b bt k s thm khng giao ph v nhng s sa i ca nhng hng.
Danh sch 13.3 cho thy mt chng trnh m thm, iu chnh, v xa nhng i tng DataRowView t mt DataView.Chng trnh ny cng trnh by nhng thuc tnh IsNew v IsEdit ca nhng i tng DataRowView. N cho bit liu c phi DataRowView l mi v ang c sa i hay khng.
Danh sch 13.3: ADDMODIFYANDREMOVEDATAROWVIEWS.CS
/* AddModifyAndRemoveDataRowViews.cs illustrates how to add, modify, and remove DataRowView objects from a DataView */
using System; using System.Data; using System.Data.SqlClient;
class AddModifyAndRemoveDataRowViews { public static void DisplayDataRow( DataRow myDataRow, DataTable myDataTable ) { Console.WriteLine("\nIn DisplayDataRow()"); foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]); } }
public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Customers"];
// set up the filter expression string filterExpression = "Country = 'UK'";
// create a DataView object named customersDV DataView customersDV = new DataView(); customersDV.Table = customersDT; customersDV.RowFilter = filterExpression;
// add a new DataRowView (adds a DataRow to the DataTable) Console.WriteLine("\nCalling customersDV.AddNew()"); DataRowView customerDRV = customersDV.AddNew(); customerDRV["CustomerID"] = "J7COM"; customerDRV["CompanyName"] = "J7 Company"; customerDRV["Country"] = "UK"; Console.WriteLine("customerDRV[\" CustomerID\"] = " + customerDRV["CustomerID"]); Console.WriteLine("customerDRV[\" CompanyName\"] = " + customerDRV["CompanyName"]); Console.WriteLine("customerDRV[\" Country\"] = " + customerDRV["Country"]); Console.WriteLine("customerDRV.IsNew = " + customerDRV.IsNew); Console.WriteLine("customerDRV.IsEdit = " + customerDRV.IsEdit); customerDRV.EndEdit(); // get and display the underlying DataRow DataRow customerDR = customerDRV.Row; DisplayDataRow(customerDR, customersDT);
AROUT Widgets Inc. UK CONSH Consolidated Holdings UK
ISLAT Island Trading UK
NORTS North/South UK
SEVES Seven Seas Imports UK
J7COM J7 Company UK
TO NHNG I TNG DataView CON:
Bn c th to ra mt DataView con t mt DataRowView cha s dng phng thc CreateChildView().V ri Bn c th xem nhng i tng DataRowView DataView con. gi phng thc CreateChildView(),u tin bn phi thm mt DataRelation vo Dataset m nh ngha mt mi quan h gia hai i tng DataTable nm bn di. (xem Chng 12, " nh hng v sa i D liu lin quan ", c thng tin v nhng i tng DataRelation.)
Chng ta hy xem xt mt v d. Gi thit bn c hai i tng DataTable c tn customersDT v ordersDT . Cng gi thit bn c thm DataRelation sau y vo Dataset m nh ngha mt mi quan h gia customersDT v ordersDT:
Cui cng, gi thit bn c mt DataView c tn customersDV xem nhng khch hng c mt ct Country l UK. V ri Bn c th gi phng thc CreateChildView() t mt DataRowView trong customersDV to ra mt DataView con; ch rng tn ca DataRelation (CustomersOrders) c chuyn cho phng thc CreateChildView():
DataView ordersDV cho php bn truy cp nhng hng con t DataTable ordersDT. i tng cha trong v d ny l DataRowView u tin t customersDV c mt CustomerID l AROUT. DataView ordersDV con cha nhng i tng DataRowView vi nhng chi tit ca n t cho khch hng AROUT.
Ghi ch : Phng thc CreateChildView() b qu ti. Phin bn khc ca phng thc ny chp nhn mt i tng DataRelation nh tham s.
lit k 13.4 trnh by mt chng trnh v d y
Danh sch 13.4: CREATECHILDDATAVIEW.CS
/* CreateChildDataView.cs illustrates how to create a child DataView */
using System; using System.Data; using System.Data.SqlClient;
class CreateChildDataView { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers;" + "SELECT OrderID, CustomerID " + "FROM Orders;"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet); mySqlConnection.Close(); myDataSet.Tables["Table"].TableName = "Customers"; myDataSet.Tables["Table1"].TableName = "Orders"; DataTable customersDT = myDataSet.Tables["Customers"]; DataTable ordersDT = myDataSet.Tables["Orders"]; // add a DataRelation object to myDataSet DataRelation customersOrdersDataRel = new DataRelation( "CustomersOrders", customersDT.Columns["CustomerID"], ordersDT.Columns["CustomerID"] ); myDataSet.Relations.Add( customersOrdersDataRel );
// create a DataView object named customersDV DataView customersDV = new DataView(); customersDV.Table = customersDT; customersDV.RowFilter = "Country = 'UK'"; customersDV.Sort = "CustomerID";
// display the first row in the customersDV DataView object Console.WriteLine("Customer:"); for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(customersDV[0][count]); }
// create a child DataView named ordersDV that views // the child rows for the first customer in customersDV DataView ordersDV = customersDV[0].CreateChildView("CustomersOrders");
// display the child rows in the customersDV DataView object Console.WriteLine("\nOrderID's of the orders placed by this customer:"); foreach (DataRowView ordersDRV in ordersDV) { Console.WriteLine(ordersDRV["OrderID"]); } } } u ra t chng trnh ny nh sau: Customer: AROUT Around the Horn UK
OrderID's of the orders placed by this customer: 10355 10383 10453 10558 10707 10741 10743 10768 10793 10864 10920 10953 11016
LP DataViewManager:
Mt DataViewManager cho php bn tp trung qun l nhiu i tng DataView trong mt Dataset. Mt DataViewManager cng cho php bn to ra nhng i tng DataView trong thi gian chy. Bng 13.6 cho thy mt s nhng thuc tnh DataViewManager.
Bng 13.6: nhng thuc tnh DataViewManager
Thuc tnh Kiu d liu M t DataSet DataSet ly hay gn Dataset c dng bi DataViewManager ca bn. DataViewSettings DataViewSettingCollection Ly DataViewSettingCollection cho mi DataTable trong Dataset ca bn. Mt DataViewSettingCollection gip bn truy cp n nhng thuc tnh ca DataView cho mi DataTable.
Mt trong s nhng phng thc ca DataViewManager l CreateDataView(). N to ra mt DataView mi cho DataTable c ch nh. DataTable c chuyn qua nh mt tham s ti phng thc CreateDataView(). Kiu tr v ca n l DataView.
Mt trong s nhng s kin DataViewManager l ListChanged. N pht khi khi danh sch c qun l bi mt DataView trong DataViewManager ca bn thay i.B x l s kin ca n l ListChangedEventHandler.
To ra v s dng mt i tng DataViewManager
To ra mt DataViewManager, Bn s dng mt trong s b khi dng sau y:
Vi myDataSet ch nh Dataset c dng bi i tng DataViewManager. N gn thuc tnh Dataset ca i tng DataViewManager mi ti myDataSet.
Chng ta hy xemxt mt v d v to ra v s dng mt DataViewManager. Gi thit bn c mt Dataset c tn myDataSet, c cha mt DataTable c c lu tr vi nhng hng t bng Customers. V d sau y to ra mt i tng DataViewManager c tn myDVM, MyDataSet chuyn qua ti b khi dng:
DataViewManager myDVM = new DataViewManager(myDataSet);
V d k tip thit t nhng thuc tnh Sort v RowFilter m s c s dng sau khi mt DataView cho DataTable Customers c to ra :
Ghi nh : m trc y khng tht s to ra mt DataView; n n thun gn nhng thuc tnh ca bt k DataView no c to ra trong tng lai, m xem nhng hng t DataTable Customers.
V d sau y tht s to ra mt DataView bi s gi phng thc CreateDataView() ca DataViewManager myDVM, chuyn DataTable customersDT ti CreateDataView():
Thuc tnh Sort v RowFilter ca DataView customersDV c gn ti CustomerID v Country = ' UK' tng ng. y l nhng s thit t tng t nh nhng thit t trc trong thuc tnh DataViewSettings.
Danh sch 13.4 Trnh by mt v d y v to v s dng DataViewManager hc trong mc ny. Danh sch 13.4 Mt : USINGDATAVIEWMANAGER.CS
/* UsingDataViewManager.cs illustrates the use of a DataViewManager object */
using System; using System.Data; using System.Data.SqlClient;
class UsingDataViewManager { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Customers"];
// create a DataViewManager object named myDVM DataViewManager myDVM = new DataViewManager(myDataSet);
// set the Sort and RowFilter properties for the Customers DataTable myDVM.DataViewSettings["Customers"].Sort = "CustomerID"; myDVM.DataViewSettings["Customers"].RowFilter = "Country = 'UK'";
// display the DataViewSettingCollectionString property of myDVM Console.WriteLine("myDVM.DataViewSettingCollectionString = " + myDVM.DataViewSettingCollectionString + "\n");
// call the CreateDataView() method of myDVM to create a DataView // named customersDV for the customersDT DataTable DataView customersDV = myDVM.CreateDataView(customersDT);
// display the rows in the customersDV DataView object foreach (DataRowView myDataRowView in customersDV) { for (int count = 0; count < customersDV.Table.Columns.Count; count++) { Console.WriteLine(myDataRowView[count]); } Console.WriteLine(""); } } }
u ra ca chng trnh ny nh sau: myDVM.DataViewSettingCollectionString = <DataViewSettingCollectionString> <Customers Sort="CustomerID" RowFilter="Country = 'UK'" RowStateFilter="CurrentRows"/> </DataViewSettingCollectionString>
AROUT Around the Horn UK BSBEV B's Beverages UK
CONSH Consolidated Holdings UK
EASTC Eastern Connection UK
ISLAT Island Trading UK
NORTS North/South UK
SEVES Seven Seas Imports UK
TO MT DataView S DNG Visual Studio .NET:
Trong mc ny, bn s hc cch to ra mt DataView nh th no s dng Visual Studio .NET (VS .NET). Bn c th theo nhng bc c m t trong mc ny:
1. M VS .NET v to ra mt ng dng Windows mi t tn myDataView. 2. hin th Server Explorer, kt ni ti c s d liu Northwind ca bn, v s ko bng Customers ti form ca bn. Vic ny to ra mt i tng SqlConnection c tn sqlConnection1 v mt i tng SqlDataAdapter c tn sqlDataAdapter1. Nhng i tng ny c t trong khay bn di form ca bn. 3. Thay i thuc tnh ConnectionString ca sqlConnection1 kt ni ti c s d liu Northwind ca bn. Nh thm mt chui con cha mt khu ( Pwd= sa, hay tng t). 4. Kch vo i tng sqlDataAdapter1 trong form ca bn, v ri kch lin kt Generate Dataset ti y ca ca s nhng thuc tnh cho sqlDataAdapter1. Chp nhn nhng mc nh trong hp thoi, v kch nt Ok to ra mt i tng Dataset c tn dataSet11. 5. Ko mt i tng DataView t tab Data ca Toolbox n form ca bn. Vic ny to ra mt i tng DataView c tn dataView1. 6. Gn thuc tnh Table ca i tng dataView1 ca bn ti dataSet11.Customers s dng danh sch s xung bn phi ca thuc tnh Table; t thuc tnh RowFilter ti Country =' UK'; v t thuc tnh Sort ti CustomerID. xem Hnh 13.1.
Thit t nhng thuc tnh ca DataView1
7. Ko mt iu khin DataGrid t nhng tab Windows Form ca Toolbox n form ca bn. Vic ny to ra mt i tng DataGrid c tn dataGrid1. 8. Gn thuc tnh DataSource ca dataGrid1 ti dataView1 s dng danh sch s xung bn phi ca thuc tnh DataSource, nh trong Hnh 13.2. iu ny kt buc d liu c ct gi trong dataView1 vo dataGrid1 v cho php dataGrid1 truy cp bt k d liu no c ct gi trong dataView1.
Hnh 13.2: gn nhng thuc tnh ca dataGrid1 9. Chn View - Code v gn phng thc Form1() ca form ca bn vi m sau public Form1() { // // Required for Windows Form Designer support // InitializeComponent();
// call the Fill() method of sqlDataAdapter1 // to populate dataSet11 with a DataTable named // Customers sqlDataAdapter1.Fill(dataSet11, "Customers"); }
Bin dch v chy form ca bn bng cch nhn Ctrl + F5. Hnh 13.3 cho thy s vn hnh ca form. Ch thng tin trong form n t DataView m bn to ra.
TM TT:
Trong chng ny, bn hc cch s dng nhng i tng DataView lc v sp xp nhng hng nh th no. Li th ca mt DataView l bn c th kt buc n ti mt thnh phn trc quan nh mt iu khin DataGrid. Mt DataView ct gi nhng bn sao ca nhng hng trong mt DataTable nh nhng i tng DataRowView. Nhng i tng DataRowView cung cp s truy cp ti nhng i tng DataRow nm bn di trong mt DataTable. Bi vy, khi bn kho st v sa i ni dung ca mt DataRowView, tc l bn tht s ang lm vic vi DataRow nm bn di. Thuc tnh RowFilter ca mt DataView tng t nh mt mnh WHERE trong mt pht biu SELECT. Do bn c th s dng nhng biu thc lc rt mnh trong DataView ca bn. V d, bn c th s dng AND, OR, NOT, IN, LIKE,nhng ton t so snh, nhng ton t s hc, nhng k t i din (* v %) v nhng chc nng tng th. Bn c th tm thy ch s ca mt DataRowView trong mt DataView s dng phng thc Find() ca mt DataView. Bn cng c th ly mt mng ca nhng i tng DataRowView s dng phng thc FindRows() ca mt DataView. Mt DataViewManager cho php bn tp trung qun l nhiu i tng DataView trong mt Dataset. Mt DataViewManager cng cho php bn to ra nhng i tng DataView trong thi gian chy.