Professional Documents
Culture Documents
LapTrinhCoSoDuLieuVoi CSharp Phan 2
LapTrinhCoSoDuLieuVoi CSharp Phan 2
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");
M V NG MT KT NI:
mySqlConnection.Open();
mySqlConnection.Close();
TH D V KT NI:
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();
// display the properties of the SqlConnection object
Console.WriteLine("mySqlConnection.ConnectionString = "+
mySqlConnection.ConnectionString);
Console.WriteLine("mySqlConnection.ConnectionTimeout = "+
mySqlConnection.ConnectionTimeout);
Console.WriteLine("mySqlConnection.Database = "+
mySqlConnection.Database);
Console.WriteLine("mySqlConnection.DataSource = "+
mySqlConnection.DataSource);
Console.WriteLine("mySqlConnection.PacketSize = "+
mySqlConnection.PacketSize);
Console.WriteLine("mySqlConnection.ServerVersion = "+
mySqlConnection.ServerVersion);
Console.WriteLine("mySqlConnection.State = "+
mySqlConnection.State);
Console.WriteLine("mySqlConnection.WorkstationId = "+
mySqlConnection.WorkstationId);
// 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
Milliseconds = 0
mySqlConnection.State = Open
Closed
Kt ni ng.
Connecting
Executing
Fetching
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();
}
}
}
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");
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
THUC TNH
KIU
CommandText
string
CommandTimeout int
CommandType
CommandType
Connection
string
Tr v tn ca mt kt ni c s d liu.
DesignTimeVisible bool
Parameters
Transaction
SqlTransaction
UpdatedRowSource UpdateRowSource
PHNG THC
GI TR TR
V
M T
Cancel()
void
CreateParameter()
SqlParameter
ExecuteNonQuery()
int
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
ExecuteXmlReader()
XmlReader
Prepare()
void
PHNG THC
GI TR TR
V
M T
ResetCommandTimeout() void
Thit lp li thuc tnh CommandTimeout v gi tr mc nh.
Ch Mc d lp SqlCommand c dnh ring cho SQLServer, rt nhiu thuc tnh v phng thc tong
thch lp ny cng tng t nh cc thuc tnh v phng thc trong nhng lp OleDbCommand v
OdbcCommand.
K Bn thc s s lm tt hn khi t b T-SQL EXECUTE Command v s dng
xo 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.
GI TR
M T
Text
Table 8.4: NHNG PHNG THC TRUY XUT THNG TIN T CS D LIU
PHNG THC KIU TR
M T
V
ExecuteReader()
Table 8.4: NHNG PHNG THC TRUY XUT THNG TIN T CS D LIU
PHNG THC KIU TR
M T
V
kt qutrong mt i tng DataReader.
ExecuteScalar()
object
ExecuteXmlReader() XmlReader
/*
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
Gi tr
M t
KeyInfo
SchemaOnly
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
M t
SingleResult
Ch nh i tng Command tr v mt tp kt qu n.
SingleRow
mySqlDataReader["ProductID"]);
Console.WriteLine("mySqlDataReader[\" ProductName\"] = " +
mySqlDataReader["ProductName"]);
Console.WriteLine("mySqlDataReader[\" QuantityPerUnit\"] = " +
mySqlDataReader["QuantityPerUnit"]);
Console.WriteLine("mySqlDataReader[\" UnitPrice\"] = " +
mySqlDataReader["UnitPrice"]);
}
mySqlDataReader.Close();
mySqlConnection.Close();
}
The output from this program is as follows:
mySqlDataReader["ProductID"] = 1
mySqlDataReader["ProductName"] = Chai
mySqlDataReader["QuantityPerUnit"] = 10 boxes x 20 bags
mySqlDataReader["UnitPrice"] = 18
myDataRow[myDataColumn]);
if (myDataColumn.ToString() == "ProviderType")
{
Console.WriteLine(myDataColumn + "= " +
((System.Data.SqlDbType) myDataRow[myDataColumn]));
}
}
}
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.
M T
ColumnSize
IsUnique
Gi tr Boole true/ false: ch nh liu hai hng c th c cng gi tr trong ct hin thi
khng.
IsKey
DataType
Kiu .NET i din cho ct. bn s hc v kiu .NET trong chng ti.
AllowDBNull
ProviderType
IsAliased
IsExpression
IsIdentity
IsAutoIncrement
IsRowVersion
IsHidden
IsLong
IsReadOnly
n.
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"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT ProductID, ProductName, UnitPrice " +
"FROM Products " +
"WHERE ProductID = 1";
mySqlConnection.Open();
// 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]));
}
}
}
productsSqlDataReader.Close();
mySqlConnection.Close();
}
Bn cn phi ch nhng chi tit khc nhau cho nhng ct ProductID, ProductName, v UnitPrice trong u
ra m i theo sau:
New column details follow:
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
New column details follow:
ColumnName = ProductName
ColumnOrdinal = 1
ColumnSize = 40
NumericPrecision = 0
NumericScale = 0
IsUnique =
IsKey =
BaseCatalogName =
BaseColumnName = ProductName
BaseSchemaName =
BaseTableName =
DataType = System.String
AllowDBNull = False
ProviderType = 12
ProviderType = NVarChar
IsAliased =
IsExpression =
IsIdentity = False
IsAutoIncrement = False
IsRowVersion =
IsHidden =
IsLong = False
IsReadOnly = False
Nhng chi tit ct mi nh sau:
ColumnName = UnitPrice
ColumnOrdinal = 2
ColumnSize = 8
NumericPrecision = 0
NumericScale = 0
IsUnique =
IsKey =
BaseCatalogName =
BaseColumnName = UnitPrice
BaseSchemaName =
BaseTableName =
DataType = System.Decimal
AllowDBNull = True
ProviderType = 9
ProviderType = Money
IsAliased =
IsExpression =
IsIdentity = False
IsAutoIncrement = False
IsRowVersion =
IsHidden =
IsLong = False
IsReadOnly = False
using System;
using System.Data;
using System.Data.OleDb;
class ExecuteTableDirect
{
public static void Main()
{
OleDbConnection myOleDbConnection =
new OleDbConnection(
"Provider=SQLOLEDB;server=localhost;database=Northwind;" +
"uid=sa;pwd=sa"
);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
// set the CommandType property of the OleDbCommand object to
// TableDirect
myOleDbCommand.CommandType = CommandType.TableDirect;
// set the CommandText property of the OleDbCommand object to
// the name of the table to retrieve from
myOleDbCommand.CommandText = "Products";
myOleDbConnection.Open();
OleDbDataReader myOleDbDataReader = myOleDbCommand.ExecuteReader();
// only read the first 5 rows from the OleDbDataReader object
for (int count = 1; count <= 5; count++)
{
myOleDbDataReader.Read();
Console.WriteLine("myOleDbDataReader[\" ProductID\"] = " +
myOleDbDataReader["ProductID"]);
Console.WriteLine("myOleDbDataReader[\" ProductName\"] = " +
myOleDbDataReader["ProductName"]);
Console.WriteLine("myOleDbDataReader[\" QuantityPerUnit\"] = " +
myOleDbDataReader["QuantityPerUnit"]);
Console.WriteLine("myOleDbDataReader[\" UnitPrice\"] = " +
myOleDbDataReader["UnitPrice"]);
}
myOleDbDataReader.Close();
myOleDbConnection.Close();
}
bn ch chng trnh ny ch hin th nm hng u trong bng Products, mc d tt c nhng hng u
c truy xut
The output from this program is as follows:
myOleDbDataReader["ProductID"] = 1
myOleDbDataReader["ProductName"] = Chai
myOleDbDataReader["QuantityPerUnit"] = 10 boxes x 20 bags
myOleDbDataReader["UnitPrice"] = 18
myOleDbDataReader["ProductID"] = 2
myOleDbDataReader["ProductName"] = Chang
myOleDbDataReader["QuantityPerUnit"] = 24 - 12 oz bottles
myOleDbDataReader["UnitPrice"] = 19
myOleDbDataReader["ProductID"] = 3
myOleDbDataReader["ProductName"] = Aniseed Syrup
myOleDbDataReader["QuantityPerUnit"] = 12 - 550 ml bottles
myOleDbDataReader["UnitPrice"] = 10
myOleDbDataReader["ProductID"] = 4
myOleDbDataReader["ProductName"] = Chef Anton's Cajun Seasoning
myOleDbDataReader["QuantityPerUnit"] = 48 - 6 oz jars
myOleDbDataReader["UnitPrice"] = 22
myOleDbDataReader["ProductID"] = 5
myOleDbDataReader["ProductName"] = Chef Anton's Gumbo Mix
myOleDbDataReader["QuantityPerUnit"] = 36 boxes
myOleDbDataReader["UnitPrice"] = 21.35
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.
Bng 8.7 trnh by s m t v nhng t kha s dng trong mnh FOR XML.
M t
FOR XML
RAW
AUTO
EXPLICIT
M t
XMLDATA
ELEMENTS
BINARY
BASE64
{
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"/>
Phng thc
Kiu M t
tr v
ExecuteNonQuery() int
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".
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:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
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:
mySqlCommand.CommandText =
"CREATE TABLE MyPersons (" +
" PersonID int CONSTRAINT PK_Persons PRIMARY KEY," +
" FirstName nvarchar(15) NOT NULL," +
" LastName nvarchar(15) NOT NULL," +
" DateOfBirth datetime" +
")";
Tip theo, bn gi phng thc ExecuteNonQuery() thc thi pht biu CREATE TABLE:
int result = mySqlCommand.ExecuteNonQuery();
do mt pht biu CREATE TABLE khng nh hng bt k hng no, ExecuteNonQuery() tr v gi tr -1.
Th d tip theo thc thi mt pht biu ALTER TABLE thm mt kha ph rng buc ti bng MyPersons:
mySqlCommand.CommandText =
"ALTER TABLE MyPersons " +
"ADD EmployerID nchar(5) CONSTRAINT FK_Persons_Customers " +
"REFERENCES Customers(CustomerID)";
result = mySqlCommand.ExecuteNonQuery();
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");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// 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:
M t
BigInt
Binary
Bit
Char
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
Float
Image
Int
Money
NChar
Ntext
NVarChar
Real
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
Thnh vin
M t
SmallMoney
Text
Timestamp
TinyInt
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
VarChar
Variant
Mt kiu d liu m c th cha nhng s, nhng chui, nhng byte hay nhng gi tr
ngy thng.
)
vic duy nht cn li l thc hin cu lnh SQL.
mySqlCommand.Parameters.Add(
"@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add(
"@MyDiscontinued", SqlDbType.Bit).Value = 1;
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.
mySqlCommand.CommandText =
"EXECUTE AddProduct @MyProductID OUTPUT, @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";
// step 2: add the required parameters to the Command object
mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
mySqlCommand.Parameters["@MyProductID"].Direction =
ParameterDirection.Output;
mySqlCommand.Parameters.Add(
"@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
mySqlCommand.Parameters.Add(
"@MySupplierID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add(
"@MyCategoryID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add(
"@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
mySqlCommand.Parameters.Add(
"@MyUnitPrice", SqlDbType.Money).Value = 5.99;
mySqlCommand.Parameters.Add(
"@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
mySqlCommand.Parameters.Add(
"@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add(
"@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add(
"@MyDiscontinued", SqlDbType.Bit).Value = 1;
// 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.
/*
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.
*/
CREATE PROCEDURE AddProduct2
@MyProductName nvarchar(40),
@MySupplierID int,
@MyCategoryID int,
@MyQuantityPerUnit nvarchar(20),
@MyUnitPrice money,
@MyUnitsInStock smallint,
@MyUnitsOnOrder smallint,
@MyReorderLevel smallint,
@MyDiscontinued bit
AS
- 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:
mySqlCommand.CommandText =
"EXECUTE @MyProductID = AddProduct2 @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";
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
mySqlDataReader["ProductName"] = Widget
mySqlDataReader["UnitPrice"] = 5.99
New ProductID = 83
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.
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
FieldCount
int
Thuc tnh
Kiu M t
IsClosed
RecordsAffected int
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 M t
v
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
GetChar()
char
Tr li gi tr ca ct c ch r nh mt char.
GetChars()
long
GetDataTypeName() string
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
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
GetSchemaTable()
DataTable
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()
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
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
IsDBNull()
bool
NextResult()
bool
Read()
bool
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:
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT TOP 5 ProductID, ProductName, UnitPrice, " +
"UnitsInStock, Discontinued " +
"FROM Products " +
"ORDER BY ProductID";
mySqlConnection.Open();
SqlDataReader productsSqlDataReader =
mySqlCommand.ExecuteReader();
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.
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");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT TOP 5 ProductID, ProductName, UnitPrice, " +
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
Byte
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
double
Double
float
Single
Guid
Guid
int
Int32
long
Int64
sbyte
SByte
short
Int16
string
String
uint
UInt32
ulong
UInt64
ushort
UInt16
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
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.
ProductID
int
GetInt32()
int
ProductName nvarchar
GetString()
string
UnitPrice
GetDecimal()
decimal
UnitsInStock smallint
GetInt16()
short
Discontinued bit
GetBoolean()
bool
money
}
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.
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
SqlBoolean
Mt s nguyn vi mt gi tr 1 hoc 0 .
SqlByte
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 -1038 + 1 v 1038 - 1.
SqlDouble
SqlGuid
Mt gi tr s nguyn mu (16 byte) v duy nht ngang qua tt c cc my tnh v nhng mng.
SqlInt16
SqlInt32
SqlInt64
SqlMoney
SqlSingle
SqlString
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*
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*
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.
int
GetInt32()
SqlInt32
ProductName
nvarchar
GetSqlString()
SqlString
UnitPrice
money
GetSqlMoney()
SqlMoney
UnitsInStock
smallint
GetSqlInt16()
SqlInt16
Discontinued
bit
GetSqlBoolean()
SqlBoolean
while (productsSqlDataReader.Read())
{
SqlInt32 productID =
productsSqlDataReader.GetSqlInt32(productIDColPos);
Console.WriteLine("productID = " + productID);
SqlString productName =
productsSqlDataReader.GetSqlString(productNameColPos);
Console.WriteLine("productName = " + productName);
SqlMoney unitPrice =
productsSqlDataReader.GetSqlMoney(unitPriceColPos);
Console.WriteLine("unitPrice = " + unitPrice);
SqlInt16 unitsInStock =
productsSqlDataReader.GetSqlInt16(unitsInStockColPos);
Console.WriteLine("unitsInStock = " + unitsInStock);
SqlBoolean discontinued =
productsSqlDataReader.GetSqlBoolean(discontinuedColPos);
Console.WriteLine("discontinued = " + discontinued);
}
Danh sch 9.3 s dng vng lp "while" ny.
/*
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"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT TOP 5 ProductID, ProductName, UnitPrice, " +
"UnitsInStock, Discontinued " +
"FROM Products " +
"ORDER BY ProductID";
mySqlConnection.Open();
SqlDataReader productsSqlDataReader =
mySqlCommand.ExecuteReader();
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);
SqlString productName =
productsSqlDataReader.GetSqlString(productNameColPos);
Console.WriteLine("productName = " + productName);
SqlMoney unitPrice =
productsSqlDataReader.GetSqlMoney(unitPriceColPos);
Console.WriteLine("unitPrice = " + unitPrice);
SqlInt16 unitsInStock =
productsSqlDataReader.GetSqlInt16(unitsInStockColPos);
Console.WriteLine("unitsInStock = " + unitsInStock);
SqlBoolean discontinued =
productsSqlDataReader.GetSqlBoolean(discontinuedColPos);
Console.WriteLine("discontinued = " + discontinued);
}
productsSqlDataReader.Close();
mySqlConnection.Close();
}
}
u ra ca chng trnh ny nh sau:
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
C NHNG GI TR NULL:
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:
decimal unitPrice =
productsSqlDataReader.GetDecimal(unitPriceColPos);
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
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");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to
// the mutliple SELECT statements
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;";
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
// 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
mySqlDataReader[0] = 10248
mySqlDataReader[1] = VINET
mySqlDataReader[0] = 10249
mySqlDataReader[1] = TOMSP
mySqlDataReader[0] = 10250
mySqlDataReader[1] = HANAR
mySqlDataReader[0] = 10251
mySqlDataReader[1] = VICTE
mySqlDataReader[0] = 10252
mySqlDataReader[1] = SUPRD
mySqlDataReader[0] = 10253
mySqlDataReader[1] = HANAR
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");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to
// the INSERT, UPDATE, and DELETE statements
mySqlCommand.CommandText =
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES ('J5COM', 'Jason 5 Company');" +
"SELECT CustomerID, CompanyName " +
"FROM Customers " +
"WHERE CustomerID = 'J5COM';" +
"UPDATE Customers " +
"SET CompanyName = 'Another Jason Company' " +
"WHERE CustomerID = 'J5COM';" +
"SELECT CustomerID, CompanyName " +
"FROM Customers " +
"WHERE CustomerID = 'J5COM';" +
"DELETE FROM Customers " +
"WHERE CustomerID = 'J5COM';";
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
// 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
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.
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
ContinueUpdateOnError bool
DeleteCommand
SqlCommand
InsertCommand
SqlCommand
MissingMappingAction
MissingMappingAction
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
Mc nh l Add.
SelectCommand
SqlCommand
TableMappings
UpdateCommand
SqlCommand
Kiu tr v
M t
Fill()
int
FillSchema()
DataTable
DataTable[]
int
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.
EVENT HANDLER
i tng s l s kin
M t
FillError
FillErrorEventHandler
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,
2,
3,
4,
SqlDataAdapter()
SqlDataAdapter(SqlCommand mySqlCommand)
SqlDataAdapter(string selectCommandString, SqlConnection mySqlConnection)
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) :
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.
Kiu
M t
CaseSensitive
bool
DataSetName
string
DefaultViewManager DataViewManager
EnforceConstraints
bool
ExtendedProperties
PropertyCollection
HasErrors
bool
Locale
CultureInfo
Namespace
string
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
Relations
Tables
DataTableCollection
void
BeginInit()
void
Clear()
void
Clone()
DataSet
Copy()
DataSet
EndInit()
void
GetChanges()
DataSet
GetXml()
string
GetXmlSchema()
string
HasChanges()
bool
Merge()
void
ReadXml()
ReadXmlSchema() void
RejectChanges()
void
Reset()
void
WriteXml()
void
WriteXmlSchema() void
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)
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.
______________________________________________________________________________________
i tng myDataTable.
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("ProductID = " + myDataRow["ProductID"]);
Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
}
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
UnitPrice = 22
ProductID = 5
ProductName = Chef Anton's Gumbo Mix
UnitPrice = 21.35
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
ProductName = Vegie-spread
Total = 20
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);
// change the CommandText property of the SelectCommand
mySqlDataAdapter.SelectCommand.CommandText =
"SELECT CustomerID, CompanyName " +
"FROM Customers " +
"WHERE CustomerID = 'ALFKI'";
numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Customers");
Console.WriteLine("numberOfRows = " + numberOfRows);
mySqlConnection.Close();
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]);
}
}
}
}
}
u ra t chng trnh ny nh sau:
numberOfRows = 2
numberOfRows = 1
Reading from the Products DataTable
ProductID = 1
ProductName = Chai
UnitPrice = 18
ProductID = 2
ProductName = Chang
UnitPrice = 19
Reading from the Customers DataTable
CustomerID = ALFKI
CompanyName = Alfreds Futterkiste
mySqlDataAdapter2.SelectCommand.CommandText =
"SELECT CustomerID, CompanyName " +
"FROM Customers " +
"WHERE CustomerID = 'ALFKI'";
numberOfRows = mySqlDataAdapter2.Fill(myDataSet, "Customers");
Console.WriteLine("numberOfRows = " + numberOfRows);
mySqlConnection.Close();
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]);
}
}
}
}
u ra t chng trnh ny nh sau:
numberOfRows = 2
numberOfRows = 1
Reading from the Products DataTable
ProductID = 1
ProductName = Chai
UnitPrice = 18
ProductID = 2
ProductName = Chang
UnitPrice = 19
Reading from the Customers DataTable
CustomerID = ALFKI
CompanyName = Alfreds Futterkiste
M t
Add
AddWithKey
Error
Ignore
Hng s
M t
DiffGram
IgnoreSchema
WriteSchema
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.
M t
Auto
DiffGram
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 .
"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
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Customers");
mySqlConnection.Close();
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():
DataTableMapping myDataTableMapping =
mySqlDataAdapter.TableMappings.Add("Customers", "Cust");
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:
Console.WriteLine("myDataTableMapping.SourceTable = " +
myDataTableMapping.SourceTable);
Console.WriteLine("myDataTableMapping.DataSetTable = " +
myDataTableMapping.DataSetTable);
V d ny hin th nh sau:
myDataTableMapping.DataSetTable = Cust
myDataTableMapping.SourceTable = Customers
Bn cng cn phi thay i thuc tnh TableName ca i tng DataTable trong Dataset ca bn gi cho
nhng tn vng chc:
myDataSet.Tables["Customers"].TableName = "Cust";
Mo nh : iu quan trng l bn phi thay i TableName v nu khng n s gi tn nguyn bn ca
Customers, v l mt cht rc ri khi bn ch nh nh x t Customers n Cust trc .
Tip theo, t b danh ct CustomerID l MyCustomer, Bn gi phng thc Add() thng qua thuc tnh
ColumnMappings ca myDataTableMapping:
myDataTableMapping.ColumnMappings.Add("CustomerID", "MyCustomer");
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
/*
CustomerID = ALFKI
CompanyName = Alfreds Futterkiste
Address = Obere Str. 57
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.
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.
Danh sch 10.14: MYDATASET.XSD
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="MyDataSet"
targetNamespace="http://tempuri.org/MyDataSet.xsd" elementFormDefault="qualified"
attributeFormDefault="qualified"
xmlns="http://tempuri.org/MyDataSet.xsd"
xmlns:mstns="http://tempuri.org/MyDataSet.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="MyDataSet" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="Customers">
<xs:complexType>
<xs:sequence>
<xs:element name="CustomerID" type="xs:string" />
<xs:element name="CompanyName" type="xs:string" />
<xs:element name="ContactName" type="xs:string" minOccurs="0" />
<xs:element name="ContactTitle" type="xs:string" minOccurs="0" />
<xs:element name="Address" type="xs:string" minOccurs="0" />
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 .
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.
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.
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
CaseSensitive bool
M T
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.
THUC
TNH
KIU
M T
Constraints
ConstraintCollection
DataSet
DataSet
HasErrors
bool
PrimaryKey
DataColumn[]
Rows
DataRowCollection
TableName
string
Kiu tr
v
M t
AcceptChanges() void
Clear()
void
Clone()
Compute()
object
GetChanges()
GetErrors()
Tnh ton biu thc cho trn nhng hng hin thi thng qua iu kin lc.
LoadDataRow() DataRow
NewRow()
DataRow
RejectChanges() void
Select()
M t
DataRowChangeEventHandler
RowChanged
DataRowChangeEventHandler
RowDeleting
DataRowChangeEventHandler
Bin c
B s l bin c
M t
DataTable.
RowDeleted
DataRowChangeEventHandler
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
ItemArray
object[]
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
Kiu tr v
M t
AcceptChanges()
void
BeginEdit()
void
CancelEdit()
void
ClearErrors()
void
Delete()
void
Xa i tng DataRow.
EndEdit()
void
GetChildRows()
DataRow[]
GetColumnError()
string
DataRow
GetParentRows()
DataRow[]
Phng thc
Kiu tr v
M t
IsNull()
bool
RejectChanges()
void
SetNull()
void
SetParentRow()
void
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
AutoIncrementSeed long
AutoIncrementStep long
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
ColumnMapping
DataType
Type
DafaultValue
object
MaxLength
int
Ordinal
int
ReadOnly
bool
Table
DataTable
Unique
bool
Bn s thy nhng s dng mt s thuc tnh , phng thc v nhng s kin ny sau trong chng ny.
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 .
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.
________________________________________________________________________________________
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:
myDataSet.Tables["Order Details"].PrimaryKey =
new DataColumn[]
{
myDataSet.Tables["Order Details"].Columns["OrderID"],
myDataSet.Tables["Order Details"].Columns["ProductID"]
};
V d sau y s dng phng php Add() thc hin cng cng vic:
myDataSet.Tables["Order Details"].Constraints.Add(
"Primary key constraint",
new DataColumn[]
{
myDataSet.Tables["Order Details"].Columns["OrderID"],
myDataSet.Tables["Order Details"].Columns["ProductID"]
},
true
);
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 .
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"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT ProductID, ProductName " +
"FROM Products;" +
"SELECT OrderID " +
"FROM Orders;" +
"SELECT OrderID, ProductID, UnitPrice " +
"FROM [Order Details];";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet);
mySqlConnection.Close();
myDataSet.Tables["Table"].TableName = "Products";
myDataSet.Tables["Table1"].TableName = "Orders";
myDataSet.Tables["Table2"].TableName = "Order Details";
// 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");
myDataColumn.MaxLength = 40
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
Reading from the Orders DataTable:
myPrimaryKey = OrderID
myDataColumn.ColumnName = OrderID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = True
Reading from the Order Details DataTable:
myPrimaryKey = OrderID
myPrimaryKey = ProductID
myDataColumn.ColumnName = OrderID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
myDataColumn.ColumnName = ProductID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
myDataColumn.ColumnName = UnitPrice
myDataColumn.DataType = System.Decimal
myDataColumn.AllowDBNull = True
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
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:
DataTable[] FillSchema(DataSet myDataSet, SchemaType mySchemaType)
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
Source
mySqlConnection.Open();
mySqlDataAdapter.FillSchema(myDataSet, SchemaType.Mapped);
mySqlConnection.Close();
myDataSet.Tables["Table"].TableName = "Products";
myDataSet.Tables["Table1"].TableName = "Orders";
myDataSet.Tables["Table2"].TableName = "Order Details";
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"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT ProductID, ProductName " +
"FROM Products;" +
"SELECT OrderID " +
"FROM Orders;" +
"SELECT OrderID, ProductID, UnitPrice " +
"FROM [Order Details];";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.FillSchema(myDataSet, SchemaType.Mapped);
mySqlConnection.Close();
myDataSet.Tables["Table"].TableName = "Products";
myDataSet.Tables["Table1"].TableName = "Orders";
myDataSet.Tables["Table2"].TableName = "Order Details";
// 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");
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = True
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = True
myDataColumn.Unique = True
myDataColumn.ColumnName = ProductName
myDataColumn.DataType = System.String
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = 40
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
Reading from the Orders DataTable:
myPrimaryKey = OrderID
myConstraint.IsPrimaryKey = True
myDataColumn.ColumnName = OrderID
myDataColumn.ColumnName = OrderID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = True
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = True
myDataColumn.Unique = True
Reading from the Order Details DataTable:
myPrimaryKey = OrderID
myPrimaryKey = ProductID
myConstraint.IsPrimaryKey = True
myDataColumn.ColumnName = OrderID
myDataColumn.ColumnName = ProductID
myDataColumn.ColumnName = OrderID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
myDataColumn.ColumnName = ProductID
myDataColumn.DataType = System.Int32
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
myDataColumn.ColumnName = UnitPrice
myDataColumn.DataType = System.Decimal
myDataColumn.AllowDBNull = False
myDataColumn.AutoIncrement = False
myDataColumn.AutoIncrementSeed = 0
myDataColumn.AutoIncrementStep = 1
myDataColumn.MaxLength = -1
myDataColumn.ReadOnly = False
myDataColumn.Unique = False
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);
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
OriginalRows
Unchanged
"ORDER BY ProductID;" +
"SELECT TOP 10 OrderID, ProductID, UnitPrice, Quantity " +
"FROM [Order Details] " +
"ORDER BY OrderID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet);
mySqlConnection.Close();
myDataSet.Tables["Table"].TableName = "Products";
myDataSet.Tables["Table1"].TableName = "Order Details";
// 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);
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
Hng s M t
Proposed Gi tr ct c xng, n c gn khi bn son tho mt DataRow s dng phng thc
BeginEdit() .
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
Deleted
Detached
Modified
DataRow c sa i.
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.
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() :
public static void RemoveDataRow(
DataTable myDataTable,
SqlDataAdapter mySqlDataAdapter,
SqlConnection mySqlConnection)
{
Console.WriteLine("\nIn RemoveDataRow()");
// 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");
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:
DataColumn productIDDataColumn =
productsDataTable.Columns["ProductID"];
productIDDataColumn.AllowDBNull = false;
productIDDataColumn.AutoIncrement = true;
productIDDataColumn.AutoIncrementSeed = -1;
productIDDataColumn.AutoIncrementStep = -1;
productIDDataColumn.ReadOnly = true;
productIDDataColumn.Unique = true;
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:
myUpdateCommand.CommandText =
"UPDATE Products " +
"SET " +
" ProductName = @NewProductName, " +
" UnitPrice = @NewUnitPrice " +
"WHERE ProductID = @OldProductID " +
"AND ProductName = @OldProductName " +
"AND UnitPrice = @OldUnitPrice";
Thuc tnh CommandText ca i tng Command c dng trong thuc tnh DeleteCommand nh sau:
myDeleteCommand.CommandText =
"DELETE FROM Products " +
"WHERE ProductID = @OldProductID " +
"AND ProductName = @OldProductName " +
"AND UnitPrice = @OldUnitPrice";
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() :
myInsertCommand.CommandText =
"INSERT INTO Products (" +
" ProductName, UnitPrice " +
") VALUES (" +
" @MyProductName, @MyUnitPrice" +
");" +
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.
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
*/
CREATE PROCEDURE UpdateProduct
@OldProductID int,
@NewProductName nvarchar(40),
@NewUnitPrice money,
@OldProductName nvarchar(40),
@OldUnitPrice money
AS
-- 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
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.
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 3: change the DataColumn values of the DataRow
myEditDataRow["ProductName"] = "Advanced Widget";
myEditDataRow["UnitPrice"] = 24.99;
Console.WriteLine("myEditDataRow.RowState = " +
myEditDataRow.RowState);
Console.WriteLine("myEditDataRow[\" ProductID\", " +
"DataRowVersion.Original] = " +
myEditDataRow["ProductID", DataRowVersion.Original]);
Console.WriteLine("myEditDataRow[\" ProductName\", " +
"DataRowVersion.Original] = " +
myEditDataRow["ProductName", DataRowVersion.Original]);
Console.WriteLine("myEditDataRow[\" UnitPrice\", " +
"DataRowVersion.Original] = " +
myEditDataRow["UnitPrice", DataRowVersion.Original]);
Console.WriteLine("myEditDataRow[\" ProductName\", " +
"DataRowVersion.Current] = " +
myEditDataRow["ProductName", DataRowVersion.Current]);
Console.WriteLine("myEditDataRow[\" UnitPrice\", " +
"DataRowVersion.Current] = " +
myEditDataRow["UnitPrice", DataRowVersion.Current]);
// 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:
In ModifyDataRow()
myEditDataRow.RowState = Modified
myEditDataRow["ProductID", DataRowVersion.Original] = 180
myEditDataRow["ProductName", DataRowVersion.Original] = Widget
myEditDataRow["UnitPrice", DataRowVersion.Original] = 10.99
myEditDataRow["ProductName", DataRowVersion.Current] = Advanced Widget
myEditDataRow["UnitPrice", DataRowVersion.Current] = 24.99
Calling mySqlDataAdapter.Update()
numOfRows = 1
myEditDataRow.RowState = Unchanged
In DisplayDataRow()
ProductID = 180
ProductName = Advanced Widget
UnitPrice = 24.99
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"]
};
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
SqlCommand mySelectCommand = mySqlConnection.CreateCommand();
mySelectCommand.CommandText =
"SELECT CustomerID, CompanyName, Address " +
"FROM Customers " +
"ORDER BY CustomerID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySelectCommand;
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:
Console.WriteLine(
"mySqlCommandBuilder.GetInsertCommand().CommandText =\n" +
mySqlCommandBuilder.GetInsertCommand().CommandText
);
Console.WriteLine(
"mySqlCommandBuilder.GetUpdateCommand().CommandText =\n" +
mySqlCommandBuilder.GetUpdateCommand().CommandText
);
Console.WriteLine(
"mySqlCommandBuilder.GetDeleteCommand().CommandText =\n" +
mySqlCommandBuilder.GetDeleteCommand().CommandText
);
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
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))
{
bool
DataTable
Errors
Values
object[]
SqlCommand
Errors
Exception
Row
DataRow
Thuc tnh
Kiu
M t
StatementType StatementType
Status
UpdateStatus
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() .
M t
DataRowChangeEventHandler
RowChanged
DataRowChangeEventHandler
RowDeleting
DataRowChangeEventHandler
RowDeleted
DataRowChangeEventHandler
ProposedValue object
Row
DataRow
M t
Action
Row
DataRow
ca lp ny.
V d v nhng " b iu khin phng thc" sau y, c tn RowDeletingEventHandler() v RowDeletedEventHandler(), trnh by thuc tnh Action:
public static void RowDeletingEventHandler(
object sender,
DataRowChangeEventArgs myDRCEA
)
{
Console.WriteLine("\nIn RowDeletingEventHandler()");
Console.WriteLine("myDRCEA.Action = " + myDRCEA.Action);
}
public static void RowDeletedEventHandler(
object sender,
DataRowChangeEventArgs myDRCEA
)
{
Console.WriteLine("\nIn RowDeletedEventHandler()");
Console.WriteLine("myDRCEA.Action = " + myDRCEA.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()");
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():
ModifyDataRow(customersDataTable, mySqlDataAdapter, mySqlConnection);
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:
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.
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.
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
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[]
ConstraintName
string
Ly tn ca UniqueConstraint.
bool
Table
DataTable
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:
UniqueConstraint(DataColumn myDataColumn)
UniqueConstraint(DataColumn[] myDataColumns)
UniqueConstraint(DataColumn myDataColumn, bool isPrimaryKey)
UniqueConstraint(DataColumn[] myDataColumns, bool isPrimaryKey)
UniqueConstraint(string constraintName, DataColumn myDataColumn)
UniqueConstraint(string constraintName, DataColumn[] myDataColumns)
UniqueConstraint(string constraintName, DataColumn myDataColumn, bool isPrimaryKey)
UniqueConstraint(string constraintName, DataColumn[] myDataColumns,
bool isPrimaryKey)
UniqueConstraint(string constraintName, string[] columnNames,
bool isPrimaryKey)
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.
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
DataColumn[]
ConstraintName
string
Ly tn ca i tng UniqueConstraint.
DeleteRule
Rule
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[]
RelatedTable
DataTable
Table
DataTable
UpdateRule
Rule
TO MT I TNG ForeignConstraint:
B khi dng ForeignKeyConstraint c qu ti nh sau:
ForeignKeyConstraint(DataColumn parentDataColumn, DataColumn childDataColumn)
ForeignKeyConstraint(DataColumn[] parentDataColumns,
DataColumn[] childDataColumns)
ForeignKeyConstraint(string constraintName, DataColumn parentDataColumn,
DataColumn childDataColumn)
ForeignKeyConstraint(string constraintName,
DataColumn[] parentDataColumns, DataColumn[] childDataColumns)
ForeignKeyConstraint(string constraintName, string parentDataTableName,
string[] parentDataColumnNames, string[] childDataColumnNames,
AcceptRejectRule acceptRejectRule, Rule deleteRule, Rule updateRule)
Vi :
.
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 =
(ForeignKeyConstraint)
ordersDT.Constraints["ForeignKeyConstraintCustomersOrders"];
Console.WriteLine("myFKC.AcceptRejectRule = " + myFKC.AcceptRejectRule);
Console.WriteLine("Columns:");
foreach (DataColumn myDataColumn in myFKC.Columns)
{
Console.WriteLine("" + myDataColumn);
}
Console.WriteLine("myFKC.ConstraintName = " + myFKC.ConstraintName);
Console.WriteLine("myFKC.DeleteRule = " + myFKC.DeleteRule);
Console.WriteLine("RelatedColumns:");
foreach (DataColumn relatedDataColumn in myFKC.RelatedColumns)
{
Console.WriteLine(""+ relatedDataColumn);
}
Console.WriteLine("myFKC.RelatedTable = " + myFKC.RelatedTable);
Console.WriteLine("myFKC.Table = " + myFKC.Table);
Console.WriteLine("myFKC.UpdateRule = " + myFKC.UpdateRule);
V d ny trnh by u ra sau y:
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:
Kiu d liu
ChildColumns
DataColumn[]
M t
Ly mng ca nhng i tng DataColumn con.
DataTable
DataSet
DataSet
ExtendedProperties PropertyCollection
Nested
bool
ParentColumns
DataColumn[]
ParentKeyConstraint UniqueConstraint
ParentTable
DataTable
RelationName
string
Ly tn ca i tng DataRelation.
"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 :
.
Console.WriteLine("Columns:");
foreach (DataColumn myDataColumn in myUC.Columns)
{
Console.WriteLine("" + myDataColumn);
}
Console.WriteLine("myUC.ConstraintName = " + myUC.ConstraintName);
Console.WriteLine("myUC.IsPrimaryKey = " + myUC.IsPrimaryKey);
Console.WriteLine("myUC.Table = " + myUC.Table);
u ra t m ny nh sau:
Columns:
CustomerID
myUC.ConstraintName = Constraint1
myUC.IsPrimaryKey = False
myUC.Table = Customers
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 :
Console.WriteLine("myFKC.AcceptRejectRule = " + myFKC.AcceptRejectRule);
Console.WriteLine("Columns:");
foreach (DataColumn myDataColumn in myFKC.Columns)
{
Console.WriteLine(""+ myDataColumn);
}
Console.WriteLine("myFKC.ConstraintName = " + myFKC.ConstraintName);
Console.WriteLine("myFKC.DeleteRule = " + myFKC.DeleteRule);
Console.WriteLine("RelatedColumns:");
foreach (DataColumn relatedDataColumn in myFKC.RelatedColumns)
{
Console.WriteLine("" + relatedDataColumn);
}
Console.WriteLine("myFKC.RelatedTable = " + myFKC.RelatedTable);
Console.WriteLine("myFKC.Table = " + myFKC.Table);
Console.WriteLine("myFKC.UpdateRule = " + myFKC.UpdateRule);
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
customersDA:
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";
// create a SqlCommand object to hold the INSERT
SqlCommand ordersInsertCommand = mySqlConnection.CreateCommand();
ordersInsertCommand.CommandText =
"INSERT INTO Orders (" +
" CustomerID, ShipCountry " +
") VALUES (" +
" @CustomerID, @ShipCountry" +
");" +
"SELECT @OrderID = SCOPE_IDENTITY();";
ordersInsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar,
5, "CustomerID");
ordersInsertCommand.Parameters.Add("@ShipCountry", SqlDbType.NVarChar,
15, "ShipCountry");
ordersInsertCommand.Parameters.Add("@OrderID", SqlDbType.Int,
0, "OrderID");
ordersInsertCommand.Parameters["@OrderID"].Direction =
ParameterDirection.Output;
// create a SqlCommand object to hold the UPDATE
SqlCommand ordersUpdateCommand = mySqlConnection.CreateCommand();
ordersUpdateCommand.CommandText =
"UPDATE Orders " +
"SET " +
" ShipCountry = @NewShipCountry " +
"WHERE OrderID = @OldOrderID " +
"AND CustomerID = @OldCustomerID " +
"AND ShipCountry = @OldShipCountry";
ordersUpdateCommand.Parameters.Add("@NewShipCountry",
SqlDbType.NVarChar, 15, "ShipCountry");
ordersUpdateCommand.Parameters.Add("@OldOrderID",
SqlDbType.Int, 0, "OrderID");
ordersUpdateCommand.Parameters.Add("@OldCustomerID",
SqlDbType.NChar, 5, "CustomerID");
ordersUpdateCommand.Parameters.Add("@OldShipCountry",
SqlDbType.NVarChar, 15, "ShipCountry");
ordersUpdateCommand.Parameters["@OldOrderID"].SourceVersion =
DataRowVersion.Original;
ordersUpdateCommand.Parameters["@OldCustomerID"].SourceVersion =
DataRowVersion.Original;
ordersUpdateCommand.Parameters["@OldShipCountry"].SourceVersion =
DataRowVersion.Original;
// create a SqlCommand object to hold the DELETE
SqlCommand ordersDeleteCommand = mySqlConnection.CreateCommand();
ordersDeleteCommand.CommandText =
"DELETE FROM Orders " +
"WHERE OrderID = @OldOrderID " +
"AND CustomerID = @OldCustomerID " +
"AND ShipCountry = @OldShipCountry";
ordersDeleteCommand.Parameters.Add("@OldOrderID", SqlDbType.Int,
0, "OrderID");
ordersDeleteCommand.Parameters.Add("@OldCustomerID",
SqlDbType.NChar, 5, "CustomerID");
ordersDeleteCommand.Parameters.Add("@OldShipCountry",
SqlDbType.NVarChar, 15, "ShipCountry");
ordersDeleteCommand.Parameters["@OldOrderID"].SourceVersion =
DataRowVersion.Original;
ordersDeleteCommand.Parameters["@OldCustomerID"].SourceVersion =
DataRowVersion.Original;
ordersDeleteCommand.Parameters["@OldShipCountry"].SourceVersion =
DataRowVersion.Original;
// 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:
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
customersDA.Fill(myDataSet, "Customers");
ordersDA.Fill(myDataSet, "Orders");
mySqlConnection.Close();
DataTable customersDT = myDataSet.Tables["Customers"];
DataTable ordersDT = myDataSet.Tables["Orders"];
Ch nhng i tng DataTable c tn l customersDT v ordersDT .
Nhng v d sau y gn nhng thuc tnh PrimaryKey ca customersDT V ordersDT:
customersDT.PrimaryKey =
new DataColumn[]
{
customersDT.Columns["CustomerID"]
};
ordersDT.PrimaryKey =
new DataColumn[]
{
ordersDT.Columns["OrderID"]
};
V d sau y thit lp DataColumn OrderID ca ordersDT nh mt kha chnh:
ordersDT.Columns["OrderID"].AllowDBNull = false;
ordersDT.Columns["OrderID"].AutoIncrement = true;
ordersDT.Columns["OrderID"].AutoIncrementSeed = -1;
ordersDT.Columns["OrderID"].AutoIncrementStep = -1;
ordersDT.Columns["OrderID"].ReadOnly = true;
ordersDT.Columns["OrderID"].Unique = true;
V d cui cng thm mt DataRelation vo myDataSet n ch r mt mi quan h gia customersDT v
ordersDT s dng CustomerID DataColumn:
DataRelation customersOrdersDataRel =
new DataRelation(
"CustomersOrders",
customersDT.Columns["CustomerID"],
ordersDT.Columns["CustomerID"]
);
myDataSet.Relations.Add(
customersOrdersDataRel
);
Chng trnh ModifyingRelatedData.cs thc hin m trc y trong phng thc Main().
THM NHNG I TNG DataRow VO customersDT V ordersDT:
V d sau y thm mt DataRow c tn customerDR vo customersDT; ch CustomerID c gn gi tr
J6COM:
DataRow customerDR = customersDT.NewRow();
customerDR["CustomerID"] = "J6COM";
customerDR["CompanyName"] = "J6 Company";
customersDT.Rows.Add(customerDR);
V d k tip thm mt DataRow c tn orderDR vo ordersDT; ch CustomerID cng c gn gi tr l
J6COM, cho bit y l DataRow con thuc DataRow trc y trong customersDT:
DataRow orderDR = ordersDT.NewRow();
orderDR["CustomerID"] = "J6COM";
orderDR["ShipCountry"] = "England";
ordersDT.Rows.Add(orderDR);
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.
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
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.
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
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.
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 .
Danh sch 12.2: NONNESTEDXMLFILE.XML
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<CustomerID>ALFKI</CustomerID>
<CompanyName>Alfreds Futterkiste</CompanyName>
</Table>
<Table>
<CustomerID>ANATR</CustomerID>
<CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
</Table>
<Table1>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10625</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10643</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10692</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10702</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10759</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10835</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10926</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10952</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>11011</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
</NewDataSet>
Danh sch 12.3 hin th file nestedXmlFile.xml c xut ra bi chng trnh. Ch lc ny nhng hng con
t bng Orders c lng bn trong nhng hng cha t bng Customers.
Danh sch 12.3: NESTEDXMLFILEL.CS
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<CustomerID>ALFKI</CustomerID>
<CompanyName>Alfreds Futterkiste</CompanyName>
<Table1>
<OrderID>10643</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10692</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10702</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10835</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>10952</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
<Table1>
<OrderID>11011</OrderID>
<CustomerID>ALFKI</CustomerID>
<ShipCountry>Germany</ShipCountry>
</Table1>
</Table>
<Table>
<CustomerID>ANATR</CustomerID>
<CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
<Table1>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10625</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10759</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
<Table1>
<OrderID>10926</OrderID>
<CustomerID>ANATR</CustomerID>
<ShipCountry>Mexico</ShipCountry>
</Table1>
</Table>
</NewDataSet>
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.
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.
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.
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 .
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
AllowDelete
bool
AllowEdit
bool
AllowNew
bool
ApplyDefaultSort bool
Count
int
M t
string
RowStateFilter
Sort
string
Table
DataTable
M t
AddNew()
DataViewRow
BeginInit()
void
CopyTo()
void
Delete()
void
EndInit()
void
Find()
int
FindRows()
M t
GetEnumerator() IEnumerator
ToString()
string
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
OriginalRows
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.
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
IsEdit
bool
IsNew
bool
Row
DataRow
Kiu tr M t
v
BeginEdit()
void
CancelEdit()
void
void
EndEdit()
void
hin ti ch s 1.
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:
DataRowView customerDRV = customersDV.AddNew();
customerDRV["CustomerID"] = "J7COM";
customerDRV["CompanyName"] = "J7 Company";
customerDRV["Country"] = "UK";
customerDRV.EndEdit();
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:
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:
DataRelation customersOrdersDataRel =
new DataRelation(
"CustomersOrders",
customersDT.Columns["CustomerID"],
ordersDT.Columns["CustomerID"]
);
myDataSet.Relations.Add(
customersOrdersDataRel
);
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 = customersDV[0].CreateChildView("CustomersOrders");
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
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.
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.
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.