Tải bản đầy đủ - 0 (trang)
Python Programming on Win32: Appendix C - The Python Database API Version 2.0

Python Programming on Win32: Appendix C - The Python Database API Version 2.0

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

C—

ThePythonDatabaseAPIVersion2.0

ThisappendixisadirectreproductionofVersion2.0ofthePythonDatabase

API.Thesameinformationcanbefoundat

http://www.python.org/topics/database/DatabaseAPI-2.0.html.

Footnotesarecollectedasendnotesattheendofthechapter,asintheonline

specification.



PythonDatabaseAPISpecification2.0

ThisAPIhasbeendefinedtoencouragesimilaritybetweenthePythonmodules

thataccessdatabases.Bydoingthis,wehopetoachieveaconsistencyleadingto

moreeasilyunderstoodmodules,codethatisgenerallymoreportableacross

databases,andabroaderreachofdatabaseconnectivityfromPython.

Theinterfacespecificationconsistsofseveralsections:

•Moduleinterface

•Connectionobjects

•Cursorobjects

•Typeobjectsandconstructors

•Implementationhints

•Majorchangesfrom1.0to2.0

CommentsandquestionsaboutthisspecificationmaybedirectedtotheSIGfor

DatabaseInterfacingwithPython.

FormoreinformationondatabaseinterfacingwithPythonandavailable

packagesseetheDatabaseTopicsGuideonwww.python.org.



ThisdocumentdescribesthePythonDatabaseAPISpecification2.0.The

previousVersion1.0versionisstillavailableasreference.Packagewritersare

encouragedtousethisversionofthespecificationasbasisfornewinterfaces.



ModuleInterface

Accesstothedatabaseismadeavailablethroughconnectionobjects.The

modulemustprovidethefollowingconstructorforthese:

connect(parameters…)



Constructorforcreatingaconnectiontothedatabase.ReturnsaConnection

object.Ittakesanumberofparametersthataredatabasedependent.1

Thesemoduleglobalsmustbedefined:

apilevel



StringconstantstatingthesupportedDBAPIlevel.Currentlyonlythestrings

1.0and2.0areallowed.Ifnotgiven,aDatabaseAPI1.0levelinterfaceshould

beassumed.

threadsafety



Integerconstantstatingthelevelofthreadsafetytheinterfacesupports.Possible

valuesare:

0=Threadsmaynotsharethemodule.

1=Threadsmaysharethemodule,butnotconnections.

2=Threadsmaysharethemoduleandconnections.

3=Threadsmaysharethemodule,connections,andcursors.

Sharinginthiscontextmeansthattwothreadsmayusearesourcewithout

wrappingitusingamutexsemaphoretoimplementresourcelocking.You

can'talwaysmakeexternalresourcesthread-safebymanagingaccessusing

amutex:theresourcemayrelyonglobalvariablesorotherexternalsources

thatarebeyondyourcontrol.

paramstyle



Stringconstantstatingthetypeofparametermarkerformattingexpectedbythe

interface.Possiblevaluesare:2



qmark=Question-markstyle,e.g.,…WHEREname=?

numeric=Numeric,positionalstyle,e.g.,…WHEREname=:1

named=Namedstyle,e.g.,…WHEREname=:name

format=ANSICprintfformatcodes,e.g.,…WHEREname=%s

pyformat=Pythonextendedformatcodes,e.g.,…WHEREname=%(name)s



Themoduleshouldmakeallerrorinformationavailablethroughthese

exceptionsorsubclassesthereof:

Warning



Exceptionraisedforimportantwarningssuchasdatatruncationswhileinserting,

etc.ItmustbeasubclassofthePythonStandardError(definedinthemodule

exceptions).

Error



Exceptionthatisthebaseclassofallothererrorexceptions.Youcanusethisto

catchallerrorswithonesingleexceptstatement.Warningsarenotconsidered

errorsandthusyoushouldnotusethisclassasbase.Itmustbeasubclassofthe

PythonStandardError(definedinthemoduleexceptions).

InterfaceError



Exceptionraisedforerrorsthatarerelatedtothedatabaseinterfaceratherthan

thedatabaseitself.ItmustbeasubclassofError.

DatabaseError



Exceptionraisedforerrorsthatarerelatedtothedatabase.Itmustbeasubclass

ofError.

DataError



Exceptionraisedforerrorsthatareduetoproblemswiththeprocesseddatalike

divisionbyzero,numericvalueoutofrange,etc.Itmustbeasubclassof

DatabaseError.

OperationalError



Exceptionraisedforerrorsthatarerelatedtothedatabase'soperationandnot

necessarilyunderthecontroloftheprogrammer,e.g.,anunexpecteddisconnect

occurs,thedatasourcenameisnotfound,atransactioncan'tbeprocessed,a



memoryallocationerroroccurredduringprocessing,etc.Itmustbeasubclassof

DatabaseError.

IntegrityError



Exceptionraisedwhentherelationalintegrityofthedatabaseisaffected,e.g.,a

foreignkeycheckfails.ItmustbeasubclassofDatabaseError.

InternalError



Exceptionraisedwhenthedatabaseencountersaninternalerror,e.g.,thecursor

isnotvalidanymore,thetransactionisoutofsync,etc.Itmustbeasubclassof

DatabaseError.

ProgrammingError



Exceptionraisedforprogrammingerrors,e.g.,tablenotfoundoralreadyexists,

syntaxerrorintheSQLstatement,wrongnumberofparametersspecified,etc.It

mustbeasubclassofDatabaseError.

NotSupportedError



ExceptionraisedincaseamethodordatabaseAPIwasusedthatisnot

supportedbythedatabase,e.g.,requestinga.rollback()onaconnectionthat

doesn'tsupporttransactionorhastransactionsturnedoff.Itmustbeasubclassof

DatabaseError.

Thisistheexceptioninheritancelayout:

StandardError

|__Warning

|__Error

|__InterfaceError

|__DatabaseError

|__DataError

|__OperationalError

|__IntegrityError

|__InternalError

|__ProgrammingError

|__NotSupportedError



Thevalueoftheseexceptionsarenotdefined.Theyshouldgivetheuserafairly

goodideaofwhatwentwrong,though.



ConnectionObjects

Connectionobjectsshouldrespondtothefollowingmethods:



close()



Closetheconnectionnow(ratherthanwhenever__del__iscalled).The

connectionisunusablefromthispointforward;anError(orsubclass)exception

israisedifanyoperationisattemptedwiththeconnection.Thesameappliesto

allcursorobjectstryingtousetheconnection.

commit()



Commitsanypendingtransactiontothedatabase.Notethatifthedatabase

supportsanauto-commitfeature,thismustbeinitiallyoff.Aninterfacemethod

maybeprovidedtoturnitbackon.

Databasemodulesthatdon'tsupporttransactionsshouldimplementthis

methodwithvoidfunctionality.

rollback()



Thismethodisoptionalsincenotalldatabasesprovidetransactionsupport.3

Incaseadatabasedoesprovidetransactions,thismethodcausesthe

databasetorollbacktothestartofanypendingtransaction.Closinga

connectionwithoutcommittingthechangesfirstcausesanimplicitrollback

tobeperformed.

cursor()



ReturnsanewCursorobjectusingtheconnection.Ifthedatabasedoesn't

provideadirectcursorconcept,themodulehastoemulatecursorsusingother

meanstotheextentneededbythisspecification.4



CursorObjects

Theseobjectsrepresentadatabasecursor,whichmanagesthecontextofafetch

operation.

Cursorobjectsshouldrespondtothefollowingmethodsandattributes:

description



Thisread-onlyattributeisasequenceofseven-itemsequences.Eachofthese

sequencescontainsinformationdescribingoneresultcolumn:

(name,type_code,display_size,internal_size,precision,

scale,null_ok).ThisattributeisNoneforoperationsthatdon'treturnrowsor

ifthecursorhasnotyethadanoperationinvokedviatheexecuteXXX()method.



Thetype_codecanbeinterpretedbycomparingittotheTypeobjects

specifiedinthenextsection.

rowcount



Thisread-onlyattributespecifiesthenumberofrowsthelastexecuteXXX()

produced(forDQLstatementssuchasselect)oraffected(forDMLstatements

suchasupdateorinsert).

Theattributeis-1ifnoexecuteXXX()hasbeenperformedonthecursoror

therowcountofthelastoperationcan'tbedeterminedbytheinterface.7

callproc(procname[,parameters])



Thismethodisoptionalsincenotalldatabasesprovidestoredprocedures.3

Callsastoreddatabaseprocedurewiththegivenname.Thesequenceof

parametersmustcontainoneentryforeachargumenttheprocedureexpects.

Theresultofthecallisreturnedasmodifiedcopyoftheinputsequence.

Inputparametersareleftuntouched,outputandinput/outputparametersare

replacedwithpossiblynewvalues.

Theproceduremayalsoprovidearesultsetasoutput.Thismustthenbe

madeavailablethroughthestandardfetchXXX()methods.

close()



Closesthecursornow(ratherthanwhenever__del__iscalled).Thecursoris

unusablefromthispointforward;anError(orsubclass)exceptionisraisedif

anyoperationisattemptedwiththecursor.

execute(operation[,parameters])



Preparesandexecutesadatabaseoperation(queryorcommand).Parameters

maybeprovidedassequenceormappingandwillbeboundtovariablesinthe

operation.Variablesarespecifiedinadatabase-specificnotation(seethe

module'sparamstyleattributefordetails)5

Areferencetotheoperationisretainedbythecursor.Ifthesameoperation

objectispassedinagain,thecursorcanoptimizeitsbehavior.Thisismost

effectiveforalgorithmswherethesameoperationisused,butdifferent

parametersareboundtoit(manytimes).

Formaximumefficiencywhenreusinganoperation,it'sbesttousethe



setinputsizes()methodtospecifytheparametertypesandsizesaheadof



time.It'slegalforaparametertonotmatchthepredefinedinformation;the

implementationshouldcompensate,possiblywithalossofefficiency.

Theparametersmayalsobespecifiedasalistoftuplesto,forexample,

insertmultiplerowsinasingleoperation,butthiskindofuseis

depreciated:executemany()shouldbeusedinstead.Returnvaluesarenot

defined.

executemany(operation,seq_of_parameters)



Preparesadatabaseoperation(queryorcommand)andthenexecutesitagainst

allparametersequencesormappingsfoundinthesequence

seq_of_parameters.



Modulesarefreetoimplementthismethodusingmultiplecallstothe

execute()methodorbyusingarrayoperationstohavethedatabase

processthesequence-asawholeinonecall.Thesamecommentsasfor

execute()alsoapplyaccordinglytothismethod.Returnvaluesaren't

defined.

fetchone()



Fetchesthenextrowofaqueryresultset,returningasinglesequence,orNone

whennomoredataisavailable.6

AnError(orsubclass)exceptionisraisedifthepreviouscallto

executeXXX()doesn'tproduceanyresultsetornocallwasissued.

fetchmany([size=cursor.arraysize])



Fetchesthenextsetofrowsofaqueryresult,returningasequenceofsequences

(e.g.,alistoftuples).Anemptysequenceisreturnedwhennomorerowsare

available.

Thenumberofrowstofetchpercallisspecifiedbytheparameter.Ifitisn't

given,thecursor'sarraysizedeterminesthenumberofrowstobefetched.

Themethodshouldtrytofetchasmanyrowsasindicatedbythesize

parameter.Ifthisisn'tpossibleduetothespecifiednumberofrowsnot

beingavailable,fewerrowsmaybereturned.

AnError(orsubclass)exceptionisraisedifthepreviouscallto

executeXXX()doesn'tproduceanyresultsetornocallwasissued.



Notethereareperformanceconsiderationsinvolvedwiththesize

parameter.Foroptimalperformance,it'susuallybesttousethearraysize

attribute.Ifthesizeparameterisused,thenit'sbestforittoretainthesame

valuefromonefetchmany()calltothenext.

fetchall()



Fetchesall(remaining)rowsofaqueryresult,returningthemasasequenceof

sequences(e.g.,alistoftuples).Thecursor'sarraysizeattributecanaffectthe

performanceofthisoperation.

AnError(orsubclass)exceptionisraisedifthepreviouscallto

executeXXX()doesn'tproduceanyresultsetornocallwasissued.

nextset()



Thismethodisoptionalsincenotalldatabasessupportmultipleresultsets.It

makesthecursorskiptothenextavailableset,discardinganyremainingrows

fromthecurrentset.Iftherearenomoresets,themethodreturnsNone.

Otherwise,itreturnsatruevalueandsubsequentcallstothefetchmethods

returnrowsfromthenextresultset.

AnError(orsubclass)exceptionisraisedifthepreviouscallto

executeXXX()doesn'tproduceanyresultsetornocallwasissued.

arraysize



Thisread/writeattributespecifiesthenumberofrowsatatimetofetchwith

fetchmany().Itdefaultsto1,meaningtofetchasinglerowatatime.

Implementationsmustobservethisvaluewithrespecttothefetchmany()

methodbutarefreetointeractwiththedatabaseasinglerowatatime.It

mayalsobeusedintheimplementationofexecutemany().

setinputsizes(sizes)



ThiscanbeusedbeforeacalltoexecuteXXX()topredefinememoryareasfor

theoperation'sparameters.

sizesisspecifiedasasequence:oneitemforeachinputparameter.The

itemshouldbeaTypeobjectthatcorrespondstotheinputused,oritshould



beanintegerspecifyingthemaximumlengthofastringparameter.Ifthe

itemisNone,nopredefinedmemoryareaisreservedforthatcolumn(thisis

usefultoavoidpredefinedareasforlargeinputs).



ThismethodisusedbeforetheexecuteXXX()methodisinvoked.

Implementationsarefreetohavethismethoddonothing,andusersarefree

tonotuseit.

setoutputsize(size[,column])



Setsacolumnbuffersizeforfetchesoflargecolumns(e.g.,LONGs,BLOBs,andso

on).Thecolumnisspecifiedasanindexintotheresultsequence.Notspecifying

thecolumnsetsthedefaultsizeforalllargecolumnsinthecursor.

ThismethodisusedbeforetheexecuteXXX()mmethodisinvoked.

Implementationsarefreetohavethismethoddonothing,andusersarefree

tonotuseit.



TypeObjectsandConstructors

Manydatabasesneedtohavetheinputinaparticularformatinordertobindto

anoperation'sinputparameters.Forexample,ifaninputisdestinedforaDATE

column,itmustbeboundtothedatabaseinaparticularstringformat.Similar

problemsexistfor"RowID"columnsorlargebinaryitems(e.g.,BLOBsorRAW

columns).ThispresentsproblemsforPythonsincetheparameterstothe

executeXXX()methodareuntyped.WhenthedatabasemoduleseesaPython

stringobject,itdoesn'tknowifitshouldbeboundasasimpleCHARcolumn,asa

rawBINARYitem,orasaDATE.

Toovercomethisproblem,amodulemustprovidetheconstructorsdefinedhere

tocreateobjectsthatcanholdspecialvalues.Whenpassedtothecursor

methods,themodulecanthendetectthepropertypeoftheinputparameterand

binditaccordingly.

Acursorobject'sdescriptionattributereturnsinformationabouteachofthe

resultcolumnsofaquery.Thetype_codemustcompareequaltooneoftype

objectsdefinedhere.Typeobjectsmaybeequaltomorethanonetypecode

(e.g.,DATETIMEcouldbeequaltothetypecodesfordate,time,andtimestamp

columns;seetheimplementationhintslaterinthisappendixfordetails).

Themoduleexportsthefollowingconstructorsandsingletons:

Date(year,month,day)



Thisfunctionconstructsanobjectholdingadatevalue.



Time(hour,minute,second)



Thisfunctionconstructsanobjectholdingatimevalue.

Timestamp(year,month,day,hour,minute,second)

Thisfunctionconstructsanobjectholdingatimestampvalue.

DateFromTicks(ticks)



Thisfunctionconstructsanobjectholdingadatevaluefromthegiventicks

value(numberofsecondssincetheepoch;seethedocumentationofthestandard

Pythontimemodulefordetails).

TimeFromTicks(ticks)



Thisfunctionconstructsanobjectholdingatimevaluefromthegiventicks

value(numberofsecondssincetheepoch;seethedocumentationofthestandard

Pythontimemodulefordetails).

TimestampFromTicks(ticks)



Thisfunctionconstructsanobjectholdingatimestampvaluefromthegiven

ticksvalue(numberofsecondssincetheepoch;seethedocumentationofthe

standardPythontimemodulefordetails).

Binary(string)



Thisfunctionconstructsanobjectcapableofholdingabinary(long)string

value.

STRING

Thistypeobjectdescribescolumnsinadatabasethatarestring-based(e.g.,

CHAR).

BINARY

Thistypeobjectdescribes(long)binarycolumnsinadatabase(e.g.,LONG,RAW,

BLOBs).

NUMBER

Thistypeobjectdescribesnumericcolumnsinadatabase.

DATETIME

Thistypeobjectdescribesdate/timecolumnsinadatabase.

ROWID

Thistypeobjectdescribesthe"RowID"columninadatabase.



SQLNULLvaluesarerepresentedbythePythonNonesingletononinputand



output.

UsingUnixticksfordatabaseinterfacingcancausetroublesbecauseofthe

limiteddaterangetheycover.

ImplementationHints

Thepreferredobjecttypesforthedate/timeobjectsarethosedefinedinthe

mxDateTimepackage.Itprovidesallnecessaryconstructorsandmethodsbothat

PythonandClevel.

Thepreferredobjecttypeforbinaryobjectsarethebuffertypesavailablein

standardPythonstartingwithVersion1.5.2.PleaseseethePython

documentationfordetails.ForinformationabouttheCinterfacehavealookat

Include/bufferobject.handObjects/bufferobject.cinthePythonsource

distribution.

HereisasampleimplementationoftheUnixticksbasedconstructorsfor

date/timedelegatingworktothegenericconstructors:

importtime

defDateFromTicks(ticks):

returnapply(Date,time.localtime(ticks)[:3])

defTimeFromTicks(ticks):

returnapply(Time,time.localtime(ticks)[3:6])

defTimestampFromTicks(ticks):

returnapply(Timestamp,time.localtime(ticks)[:6])



ThisPythonclassallowsimplementingtheabovetypeobjectseventhoughthe

descriptiontypecodefieldyieldsmultiplevaluesforontypeobject:

classDBAPITypeObject:

def__init__(self,*values):

self.values=values

def__cmp__(self,other):

ifotherinself.values:

return0

ifother
return1

else:

return-1



Theresultingtypeobjectcomparesequaltoallvaluespassedtotheconstructor.



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

Python Programming on Win32: Appendix C - The Python Database API Version 2.0

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

×