Tải bản đầy đủ - 0 (trang)
Chapter 5. Adding and Modifying Data

Chapter 5. Adding and Modifying Data

Tải bản đầy đủ - 0trang

Thischapterfocusesonissuesrelatedtoaddingandediting,

andpersistingdatachangestothedatasource.Anoverviewof

someofthetopicsinthischapterfollows.

ADO.NETprovidesanautoincrementingcolumntypethat

generatesauniquevalueforeachnewrow.Thereisno

mechanismtoensurethatthevaluesareuniquefromthe

valuesproducedbyotherusers.Section5.1showshowtouse

autoincrementingcolumnstoensurethatthevaluesgenerated

bydifferentusersdonotconflict.

SQLServerhasanidentitycolumnthatisalsoan

autoincrementingcolumntype.Thisvalueisusedratherthan

theADO.NETautoincrementcolumntypewhenaddingnew

records;thereisnoautomaticwaytokeepthesevalues

synchronizedafternewrowsinaDataTablehavebeeninserted

intoaSQLServertable.Section5.2showsyouhowto

synchronizetheDataTabletothevaluesinthedatabase.

Section5.3showsyouhowtosynchronizethesevalueswitha

MicrosoftAccessdatabase.

Oracledoesnotsupportautoincrementcolumnsbutratheruses

asequence,thatis,aprocedurethatgeneratesaseriesof

uniquevalues.Section5.4showshowtosynchronize

autoincrementingcolumnsinaDataTablewithOraclesequence

valuesafterarowhasbeeninsertedintoanOracledatabase.

Section5.8showshowtoaddmaster-detailrecordstoa

DataSetwheretheprimarykeyoftheparenttableisan

autoincrementingcolumn.

AGloballyUniqueIdentifier(GUID)isa128-bitintegerthatis

statisticallyunique.Section5.9showshowtoaddrecordstoa

DataSetcontainingmaster-detailrecordswithbothparentand

childtableshavingaGUIDprimarykey.

Changingtheprimarykeyvalueinadatabaseisalittlemore

complicatedthanchangingitinaDataTableandupdatingitto

thedatabase.Whentheprimarykeyischangedinthe



DataTable,thedefaultupdatebehavioristolookforarow

matchingthemodifiedvaluefortheprimarykeyratherthanthe

original.Section5.12demonstrateshowtochangetheprimary

keyinadatabase.

Inarelationaldatabase,many-to-manyrelationshipsusea

junctiontabletojointwoothertables.Section5.14showshow

toupdatechangesmadetothetablesandrelationships

betweentherowswithoutcausingreferentialintegrityerrors.

ADataSetkeepsnoconnectionordatasourceinformation

aboutitsdatasource.ThisallowsaDataSettobeloadedwith

datafromonedatasourceandupdatedbacktoanotherdata

source,perhapsforauditingorloggingpurposes.Section5.11

showshowthisisdone.

ACommandBuildercanquicklyandeasilygenerateupdatelogic

foraDataAdapterinsmallortestapplications.A

CommandBuildercannotgeneratevalidupdatelogicifthetable

orcolumnnamescontainspecialcharactersorspaces.Section

5.17showshowtomaketheCommandBuilderdelimittableand

columnnamestoovercomethisproblem.

Althoughofquestionableusefulnessinaproduction

environment,ADO.NETallowsyoutoretrievestoredprocedure

parametersinformationatruntime.SQLServeralsoletsyoudo

thesamethingusingasystemstoredprocedure.Section5.13

showsyoubothtechniques.

Messagingallowsapplicationsrunningondisparateplatformsto

communicatewhethertheyareconnectedordisconnected.

Section5.15showshowtousemessagingtoupdatea

database.

Section5.16showshowtouseaDataViewtocontrolediting,

deleting,andinsertingdata.

SQLServer2008introducesChangeDataCapture(CDC)that

letsyouautomaticallylogallchangesmadetodataina



databasetableortoselectedcolumnsinadatabasetable.

Section5.18showsyouhowtousethisnewfeature.



Chapter5.AddingandModifyingData

Introduction

UsingAutoincrementingColumnsWithoutCausingConflicts

GettinganIdentityColumnValuefromSQLServer

GettinganAutoNumberValuefromMicrosoftAccess

GettingaSequenceValuefromOracle

ModifyingDatainaMicrosoftExcelWorkbook

ModifyingDatainaTextFile

RetrievingUpdateErrors

AddingParent/ChildRowswithAutoincrementingKeys

AddingRecordswithaGUIDPrimaryKey

InsertingMultipleRowsintoaDatabaseTableUsingT-SQLRow

Constructors

UpdatingaDataSourcewithDatafromaDifferentDataSource

UpdatingaPrimaryKeyValue

GettingStoredProcedureParameterInformationatRuntime

UpdatingaDataSetwithaMany-to-ManyRelationship

UpdatingDataAsynchronouslyUsingMessageQueuing

ControllingEdits,Deletions,orAdditionstoDatawitha

DataView

OvercomingKeywordConflictsWhenUsingaCommandBuilder

CapturingChangestoDatainaSQLServerDatabase



Recipe5.0.Introduction



Thischapterfocusesonissuesrelatedtoaddingandediting,

andpersistingdatachangestothedatasource.Anoverviewof

someofthetopicsinthischapterfollows.

ADO.NETprovidesanautoincrementingcolumntypethat

generatesauniquevalueforeachnewrow.Thereisno

mechanismtoensurethatthevaluesareuniquefromthe

valuesproducedbyotherusers.Section5.1showshowtouse

autoincrementingcolumnstoensurethatthevaluesgenerated

bydifferentusersdonotconflict.

SQLServerhasanidentitycolumnthatisalsoan

autoincrementingcolumntype.Thisvalueisusedratherthan

theADO.NETautoincrementcolumntypewhenaddingnew

records;thereisnoautomaticwaytokeepthesevalues

synchronizedafternewrowsinaDataTablehavebeeninserted

intoaSQLServertable.Section5.2showsyouhowto

synchronizetheDataTabletothevaluesinthedatabase.

Section5.3showsyouhowtosynchronizethesevalueswitha

MicrosoftAccessdatabase.

Oracledoesnotsupportautoincrementcolumnsbutratheruses

asequence,thatis,aprocedurethatgeneratesaseriesof

uniquevalues.Section5.4showshowtosynchronize

autoincrementingcolumnsinaDataTablewithOraclesequence

valuesafterarowhasbeeninsertedintoanOracledatabase.

Section5.8showshowtoaddmaster-detailrecordstoa

DataSetwheretheprimarykeyoftheparenttableisan

autoincrementingcolumn.

AGloballyUniqueIdentifier(GUID)isa128-bitintegerthatis

statisticallyunique.Section5.9showshowtoaddrecordstoa

DataSetcontainingmaster-detailrecordswithbothparentand

childtableshavingaGUIDprimarykey.

Changingtheprimarykeyvalueinadatabaseisalittlemore

complicatedthanchangingitinaDataTableandupdatingitto

thedatabase.Whentheprimarykeyischangedinthe



DataTable,thedefaultupdatebehavioristolookforarow

matchingthemodifiedvaluefortheprimarykeyratherthanthe

original.Section5.12demonstrateshowtochangetheprimary

keyinadatabase.

Inarelationaldatabase,many-to-manyrelationshipsusea

junctiontabletojointwoothertables.Section5.14showshow

toupdatechangesmadetothetablesandrelationships

betweentherowswithoutcausingreferentialintegrityerrors.

ADataSetkeepsnoconnectionordatasourceinformation

aboutitsdatasource.ThisallowsaDataSettobeloadedwith

datafromonedatasourceandupdatedbacktoanotherdata

source,perhapsforauditingorloggingpurposes.Section5.11

showshowthisisdone.

ACommandBuildercanquicklyandeasilygenerateupdatelogic

foraDataAdapterinsmallortestapplications.A

CommandBuildercannotgeneratevalidupdatelogicifthetable

orcolumnnamescontainspecialcharactersorspaces.Section

5.17showshowtomaketheCommandBuilderdelimittableand

columnnamestoovercomethisproblem.

Althoughofquestionableusefulnessinaproduction

environment,ADO.NETallowsyoutoretrievestoredprocedure

parametersinformationatruntime.SQLServeralsoletsyoudo

thesamethingusingasystemstoredprocedure.Section5.13

showsyoubothtechniques.

Messagingallowsapplicationsrunningondisparateplatformsto

communicatewhethertheyareconnectedordisconnected.

Section5.15showshowtousemessagingtoupdatea

database.

Section5.16showshowtouseaDataViewtocontrolediting,

deleting,andinsertingdata.

SQLServer2008introducesChangeDataCapture(CDC)that

letsyouautomaticallylogallchangesmadetodataina



databasetableortoselectedcolumnsinadatabasetable.

Section5.18showsyouhowtousethisnewfeature.



Recipe5.1.UsingAutoincrementing

ColumnsWithoutCausingConflicts

5.2.1.Problem

YouwanttouseanAutoIncrementcolumninatablewithout

producingvaluesthatmaybeduplicatedatthedatasourcein

recordsaddedbyotherusers.



5.2.2.Solution

UsetheAutoIncrementSeedandAutoIncrementStep

propertiesoftheAutoIncrementcolumn.

ThesolutioncreatesaDataTableandusesaDataAdapterto

loadschemaanddatafromtheHumanResources.Department

tableinAdventureWorks.TheAutoIncrementSeedand

AutoIncrementSteppropertyvaluesarebothsetto–1forthe

AutoIncrementprimarykeycolumnDepartmentID.Twonew

recordsareaddedtotheDataTable.Thecontentsofthe

DataTablearewrittentotheconsole.

TheC#codeinProgram.csintheproject

AutoIncrementWithoutConflictisshowninExample5-1.

Example5-1.File:Program.csfor

AutoIncrementWithoutConflictsolution

CodeView:

usingSystem;

usingSystem.Data;

usingSystem.Data.SqlClient;

namespaceAutoIncrementWithoutConflict

{

classProgram

{



staticvoidMain(string[]args)

{

stringsqlConnectString="DataSource=(local);"+

"Integratedsecurity=SSPI;InitialCatalog=Adven



stringsqlSelect="SELECT*FROMHumanResources.De



//CreateandfillaDataTablewithschemaanddata

DataTabledt=newDataTable();

SqlDataAdapterda=newSqlDataAdapter(sqlSelect,s

da.FillSchema(dt,SchemaType.Source);

//ConfiguretheprimarykeycolumnDepartmentID

dt.Columns["DepartmentID"].AutoIncrementSeed=-1;

dt.Columns["DepartmentID"].AutoIncrementStep=-1;

dt.PrimaryKey=newDataColumn[]{dt.Columns["Depa

da.Fill(dt);



//Addtworecords

dt.Rows.Add(newobject[]{null,"TestName1","Tes

System.DateTime.Now});

dt.Rows.Add(newobject[]{null,"TestName2","Te

System.DateTime.Now});



foreach(DataRowrowindt.Rows)

Console.WriteLine("ID={0}\tName={1},GroupN

row["DepartmentID"],row["Name"],row["Grou



Console.WriteLine();

Console.WriteLine("Pressanykeytocontinue.");

Console.ReadKey();

}

}

}

















TheoutputisshowninFigure5-1.











Figure5-1.OutputforAutoIncrementWithoutConflict

solution



5.2.3.Discussion

AnAutoIncrementcolumngeneratesaseriesofvalues

beginningwiththeAutoIncrementSeedvalueandincremented

bytheAutoIncrementStepvalueforeachnewvalue.Thislets

youeasilygenerateuniquevaluesforinteger-typecolumns.

Apotentialproblemexistswhennewrowsarebeinginserted

intoanexistingtableforanidentityfield(inSQLServer)where

thegeneratedvaluesconflictwithexistingvaluesinthetable

becauseof,perhaps,newrecordsaddedtothedatasourceby

otherusers.Inthiscase,insteadofbeinginterpretedasnew

recordsbythedatasource,theserecordsareincorrectly

interpretedasupdatesofexistingrecords.

TheproblemcanbeavoidedbysettingtheAutoIncrementSeed

valueto–1andtheAutoIncrementStepvalueto–1,thereby

generatingasequenceofnegativevaluesthatdoesnotconflict

withthevaluesgeneratedbythedatasource,aslongasthe

datasourcedoesnotgeneratenegativesequencevalues.When

thedisconnecteddataisreconciledwiththeunderlyingdata

(seeSection5.2),thedatasourcecorrectlyidentifiesthe



recordsthathavenegativeAutoIncrementfieldvaluesasnew

records,addsthemtothedatasource,andintheprocess

generatesnewvaluesfortheAutoIncrementfield.Section5.2

discussessynchronizingthesedatasource-generatedvalues

withthedisconnecteddata.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5. Adding and Modifying Data

Tải bản đầy đủ ngay(0 tr)

×