仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 970|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA编程:数据库毗连之jtds先容(待翻译)

[复制链接]
透明 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:39:27 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。Oracle收购Sun后Java前途未卜。数据|数据库|数据库毗连GettingStarted
WhataretheclassnamesoftheDriver,DataSource,ConnectionPoolDataSourceandXADataSourceimplementations?
InterfacejTDSImplementationjava.sql.Drivernet.sourceforge.jtds.jdbc.Driverjavax.sql.DataSourcenet.sourceforge.jtds.jdbcx.JtdsDataSourcejavax.sql.ConnectionPoolDataSourcenet.sourceforge.jtds.jdbcx.JtdsDataSourcejavax.sql.XADataSourcenet.sourceforge.jtds.jdbcx.JtdsDataSource^top^
WhatistheURLformatusedbyjTDS?
TheURLformatforjTDSis:
  1. jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
复制代码
where<server_type>isoneofeithersqlserverorsybase(theirmeaningisquiteobvious),<port>istheportthedatabaseserverislisteningto(defaultis1433forSQLServerand7100forSybase)and<database>isthedatabasename--JDBCterm:catalog--(ifnotspecified,theusersdefaultdatabaseisused).ThesetofpropertiessupportedbyjTDSis:
user(required)Usernametouseforlogin.WhenusinggetConnection(Stringurl,Stringuser,Stringpassword)itsnotrequiredtosetthispropertyasitispassedasparameter,butyouwillhavetosetitwhenusinggetConnection(Stringurl,Propertiesinfo)orTdsDataSource.password(required)Passwordtouseforlogin.WhenusinggetConnection(Stringurl,Stringuser,Stringpassword)itsnotrequiredtosetthispropertyasitispassedasparameter,butyouwillhavetosetitwhenusinggetConnection(Stringurl,Propertiesinfo)orTdsDataSource.TDS(default-"8.0"forSQLServer;"5.0"forSybase)TheversionofTDStobeused.TDS(TabularDataStream)istheprotocolusedbyMicrosoftSQLServerandSybasetocommunicatewithdatabaseclients.jTDScanuseTDS4.2,5.0,7.0and8.0.Version4.2isusedbySQLServer6.5andSybase10.Version5.0isusedwithSybase11onwards.Version7.0isusedbySQLServer7.0;thisprotocolalsoworkswithSQLServer2000.Version8.0isusedbySQLServer2000andSQLServer2005.
Newerdatabaseserverversionsusuallyunderstandolderprotocolversions.ThismeansthatSQLServer7.0canbeusedwithTDS4.2,butthelimitationsoftheprotocolapplyregardlessoftheserverversion(e.g.whenusingTDS4.2VARCHARsarelimitedto255characters).Asaconclusion,youmustsetthispropertyto"4.2"whenconnectingtoSQLServer6.5orSybase.Youshouldnotsetthisvalueto"7.0"or"8.0")whenconnectingtoanyversionofSybaseastheseareSQLServerspecificprotocols.Further,youshouldnotsetthisvalueto"5.0")whenconnectingtoanyversionofSQLServerasthisisaSybasespecificprotocol.
CurrentlyjTDSautomaticallyfallsbackfrom8.0to7.0(ifusedwithSQLServer7.0)andfrom5.0to4.2(withSybase10)sospecifyingthevalueforthisparameterisonlynecessaryforSQLServer6.5.cachemetadata(default-false)WhenusedwithprepareSQL=3,settingthispropertytotruewillcausethedrivertocachecolumnmetadataforSELECTstatements.Cachingthemetadatawillreducetheprocessingoverheadwhenreusingstatementsthatreturnsmallresultsetsthathavemanycolumnsbutmayleadtounexpectederrorsifthedatabaseschemachangesafterthestatementhasbeenprepared.Usewithcare.OnlyapplicabletoSQLServer(thereisnoprepareSQL=3modeforSybase).charset(default-thecharactersettheserverwasinstalledwith)Veryimportantsetting,determinesthebytevaluetocharactermappingforCHAR/VARCHAR/TEXTvalues.Appliesforcharactersfromtheextendedset(codes128-255).ForNCHAR/NVARCHAR/NTEXTvaluesdoesnthaveanyeffectsincethesearestoredusingUnicode.domainSpecifiestheWindowsdomaintoauthenticatein.Ifpresentandtheusernameandpasswordareprovided,jTDSusesWindows(NTLM)authenticationinsteadoftheusualSQLServerauthentication(i.e.theuserandpasswordprovidedarethedomainuserandpassword).Thisallowsnon-WindowsclientstologintoserverswhichareonlyconfiguredtoacceptWindoesauthentication.
Ifthedomainparameterispresentbutnousernameandpasswordareprovided,jTDSusesitsnativeSingle-Sign-OnlibraryandlogsinwiththeloggedWindowsuserscredentials(forthistoworkonewouldobviouslyneedtobeonWindows,loggedintoadomain,andalsohavetheSSOlibraryinstalled--consultREADME.SSOinthedistributiononhowtodothis).instanceNamedinstancetoconnectto.SQLServercanrunmultipleso-called"namedinstances"(i.e.differentserverinstances,runningondifferentTCPports)onthesamemachine.WhenusingMicrosofttools,selectingoneoftheseinstancesismadebyusing"<host_name><instance_name>"insteadoftheusual"<host_name>".WithjTDSyouwillhavetosplitthetwoandusetheinstancenameasaproperty.appName(default-"jTDS")Applicationname.Nopracticaluse,itsdisplayedbyEnterpriseManagerorProfilerassociatedwiththeconnection.progName(default-"jTDS")Clientlibraryname.Nopracticaluse,itsdisplayedbyEnterpriseManagerorProfilerassociatedwiththeconnection.wsid(default-theclienthostname)WorkstationID.Nopracticaluse,itsdisplayedbyEnterpriseManagerorProfilerassociatedwiththeconnection.macAddress(default-"000000000000")NetworkinterfacecardMACaddress.ItsdisplayedbyEnterpriseManagerorProfilerassociatedwiththeconnectionandisneededtoresolvesomeissuesregardingthenumberofclientsallowedbytheSQLServerlicense.TheMACaddresscannotbedeterminedautomaticallyfromJava(i.e.withoutusingnativecode)soyoullhavetospecifyityourselfifyouneedit.sendStringParametersAsUnicode(default-true)DetermineswhetherstringparametersaresenttotheSQLServerdatabaseinUnicodeorinthedefaultcharacterencodingofthedatabase.ThisseriouslyaffectsSQLServer2000performancesinceitdoesnotautomaticallycastthetypes(as7.0does),meaningthatifaindexcolumnisUnicodeandthestringissubmittedusingthedefaultcharacterencoding(ortheotherwayaround)SQLServerwillperformanindexscaninsteadofanindexseek.lastUpdateCount(default-true)IftrueonlythelastupdatecountwillbereturnedbyexecuteUpdate().Thisisusefulincaseyouareupdatingorinsertingintotablesthathavetriggers(suchasreplicatedtables);theresnowaytomakethedifferencebetweenanupdatecountreturnedbyatriggerandtheactualupdatecountbuttheactualupdatecountisalwaysthelastasthetriggersexecutefirst.Iffalseallupdatecountsarereturned;usegetMoreResults()toloopthroughthem.prepareSQL(default-3forSQLServer,1forSybase)ThisparameterspecifiesthemechanismusedforPreparedStatements.ValueDescription0SQLissenttotheservereachtimewithoutanypreparation,literalsareinsertedintheSQL(slower)1TemporarystoredproceduresarecreatedforeachuniqueSQLstatementandparametercombination(faster)2sp_executesqlisused(fast)3sp_prepareandsp_cursorprepareareusedinconjunctionwithsp_executeandsp_cursorexecute(faster,SQLServeronly)packetSize(default-4096forTDS7.0/8.0;512forTDS4.2/5.0)Thenetworkpacketsize(amultipleof512).tcpNoDelay(default-true)truetoenableTCP_NODELAYonthesocket;falsetodisableit.lobBuffer(default-32768)TheamountofLOBdatatobufferinmemorybeforecachingtodisk.ThevalueisinbytesforBlobdataandcharsforClobdata.maxStatements(default-500)Thenumberofstatementprepareseachconnectionshouldcache.Avalueof0willdisablestatementcaching.AvalueofInteger.MAX_VALUE(2147483647)willenablefastcaching(useslessmemoryandhasnooverheadassociatedwithremovingstatements);thecachewillneverreleaseanycachedstatements,soalthoughexperiencehasshownthatthisisusuallynotaproblemwithmostapplications,usewithcare.loginTimeout(default-0)Theamountoftimetowait(inseconds)forasuccessfulconnectionbeforetimingout.namedPipe(default-false)Whensettotrue,namedpipecommunicationisusedtoconnecttothedatabaseinsteadofTCP/IPsockets.Whentheservernameis"localhost"orstartswith"127.",localnamedpipes(viatheWindowsfilesystem)areused.TheseusuallyhavebetterperformancethanTCP/IPcommunication,butonlyworkwhentheSQLServerandclientareonthesamemachine.Iftheservernameisnot"localhost"or"127.something"theJCIFSlibraryisused.JCIFSisanamedpipeoverTCP/IPimplementationandrequiresWindows(NTLM)authentication,sothedomainparameterisrequired.
Thisfeaturesupportstheinstanceparameter(whichchangesthenamedpipeURL),butitdoesnotcurrentlysupportthenamedpipeatalocationotherthan/sql/queryontheserver.Theportparameterisignoredifset.xaEmulation(default-true)Whensettotrue,emulateXAdistributedtransactionsupport,whensettofalseuseexperimentaltruedistributedtransactionsupport.TruedistributedtransactionsupportisonlyavailableforSQLServer2000andrequirestheinstallationofanexternalstoredprocedureinthetargetserver(seetheREADME.XAfileinthedistributionfordetails).ssl(default-off)SpecifiesifandhowtouseSSLforsecurecommunication.ValueDescriptionoffSSLisnotrequestorused;thisisthedefaultrequestSSLisrequested;iftheserverdoesnotsupportitthenaplainconnectionisusedrequireSSLisrequested;iftheserverdoesnotsupportitthenanexceptionisthrownauthenticateSameasrequireexcepttheserverscertificatemustbesignedbyatrustedCAbatchSize(default-0forSQLServer;1000forSybase)Controlshowmanystatementsaresenttotheserverinabatch.Theactualbatchisbrokenupintopiecesthislargethataresentseparately.ThereasonforthisistoavoidSybase"hangs"causedbyrunningoutofspacewithverylargebatches.TheproblemdoesntseemtooccurwithSQLServer,hencethedefaultlimitof0(unlimited)inthiscase.useCursors(default-false)InstructsjTDStouseserversidecursorsinsteadofdirectselects(AKAfirehosecursors)forforward-onlyread-onlyresultsets(withothertypesofresultsetsserver-orclient-sidecursorsarealwaysused).
WithfirehosecursorstheSELECTqueryissentandtheserverrespondswithalltheresultingrows.Thisisthefastestapproachbutitmeansthatthedriverhastocacheallresultsifanotherrequestneedstobemadebeforeallrowshavebeenprocessed.SowhenusingmultipleStatementsperConnectionitispreferabletohaveserver-sidecursorsinstead;thesewillallowthedrivertorequestonlyalimitednumberofrowsatatime(controllablethroughthefetchSizepropertyofaStatement).Thismeansextrarequest-responsecycles,butlesscachingbythedriver.
WithSQLServerasocalledfastforward-onlycursorwillbecreatedwhenthispropertyissettotrue.WithSybaseausualforward-onlyread-onlycursoriscreated.bufferMaxMemory(default-1024)Controlstheglobalbuffermemorylimitforallconnections(inkilobytes).Whentheamountofbufferedserverresponsepacketsreachesthislimitadditionalpacketsarebufferedtodisk;thereishoweveroneexception:eachStatementgetstobufferatleast<bufferMinPackets>tomemorybeforethislimitisenforced.Thismeansthatthislimitcanandwillusuallybeexceeded.
ServerresponsesarebufferedtodiskonlywhenarequestismadeonaStatementwhileanotherStatementbelongingtothesameConnectionstillhasntprocessedallitsresults.ThesesituationscanbeavoidedinmostcasesbysettingtheuseCursorsproperty,butthiswillalsoaffectperformance.
SeealsobufferMinPackets.bufferMinPackets(default-8)Controlstheminimumnumberofpacketsperstatementtobuffertomemory.EachStatementwillbufferatleastthismanypacketsbeforebeingforcedtouseatemporaryfileifthe<bufferMaxMemory>isreached,toensuregoodperformanceevenwhenoneStatementcachesaverylargeamountofdata.
ServerresponsesarebufferedtodiskonlywhenarequestismadeonaStatementwhileanotherStatementbelongingtothesameConnectionstillhasntprocessedallitsresults.ThesesituationscanbeavoidedinmostcasesbysettingtheuseCursorsproperty,butthiswillalsoaffectperformance.
SeealsobufferMaxMemory.useLOBs(default-true)Controlswhetherlargetypes(IMAGEandTEXT/NTEXT)shouldbemappedbydefault(whenusinggetObject())toLOBsorJavatypes(Stringandbyte[]).ThedefaultJDBCtypeconstantreturnedisalsocontrolledbythisproperty:Types.BLOBforIMAGEandTypes.CLOBforTEXT/NTEXTwhentrue,Types.LONGVARBINARYforIMAGEandTypes.LONGVARCHARforTEXT/NTEXTwhenfalse.
ThisisusefulwhenprintingoutdirectlythevaluesreturnedbygetObject()(e.g.whenusingJSTLorotherframeworks),asBlobandClobdontimplementtoString()(bothbecauseitsnotrequiredandbecauseitcaneasilyleadtoOutOfMemoryErrorsinunexpectedsituations,suchaswhenloggingdata).ThedefaultsettingoftruehastheadvantagethattheamountofdatathatiscachedinmemoryforalargeobjectcanbecontrolledviathelobBufferproperty;asettingoffalsewillstillusetheBlobandClobimplementationsinternallybutthevalueswillbematerializedtomemorywhengetObject()iscalled,possiblyleadingtomemoryissues.PropertiescanbepassedtojTDSinoneofthreeways:intheURL,inthePropertiesobjectpassedtogetConnection()orbyusingtheTdsDataSourcessetters(ifconnectionsareobtainedthroughaDataSourceratherthanusingtheDriverManager).BecausethereisnoURLwhenusingtheTdsDataSourcetherearethreeotherproperties(withsettersandgetters)totaketheplaceofthoseitemsthatarepartoftheURLssyntax:serverName,portNumberanddatabaseName(theirmeaningshouldbequiteclear).
^top^
jTDSissupposedtobethefastestJDBCdriveraround.Haveyougotanyfigurestoprovethat?Orevenbetter,abenchmarkIcanrunmyself?
Actuallywedohavebenchmarkresultsfromtwodifferentbenchmarks,bothdevelopedbylargecommercialSQLServerJDBCdrivervendorstodemonstratetheperformanceoftheirowndrivers.Inouroppinionthisisbetterthanhavingabenchmarkofourown,whichcouldbedesignedinsuchawayastogivejTDStheedge.Thesebenchmarksarefreetodownloadsoweencourageyoutodoitandrunthemyourself.
WehavebenchmarkedjTDSagainstthetwomostusedcommercialdriversandofcoursetheMicrosoftdriverandtheJDBC-ODBCbridge,usingthesebenchmarks:i-netsoftwaresBenchTest2.1forMSSQLServerandJNetDirectsJDBCPerformanceBenchmark.Herearetheresultsofthei-nettest:BenchTest2.1forMSSQLServer.TheJNetDirectlicenseprecludespublicationofperformancetestresults.However,youcanrunanyofthebenchmarksyourself,theeffortisminimal.
^top^
WhichJDBCfeaturesareandwhichfeaturesarenotsupportedbyjTDS?
jTDSoffersfullsupportforallJDBC3.0features:forward-onlyandscrollable/updateableresultsets,batchupdates,preparedandcallablestatements,unlimitednumberofstatementsperconnection,completedatabaseandresultsetmetadata,andaDataSourceimplementation(whichalsoimplementsConnectionPoolDataSourceandXADataSource).Featuressuchasgeneratedkeysretrieval,namedstoredprocedureparameters,andsavepointsarealsoimplemented.
TheonlymajorfeaturesmissingfromjTDSareconnectionpoolingandrowsets;thereasonforleavingtheseoutisthattherearefreeimplementationsavailable,probablymuchbetterthananythingwecouldcomeupwith.CheckoutthejTDSfeaturematrixformoredetails.
^top^
CanjTDSbeusedinamultithreadedapplication?
Asageneralprinciplewetryandkeepsynchronizationtoaminimumbothforperformanceanddeadlockreasons.TheonlypartofjTDSweguaranteeisthreadsafeistheConnectionobject,andmultithreadedaccesstoStatementsisdiscouraged(exceptforissuingcancels).
Asaconclusiontheonlysafemultithreadingscenariosarethese:(i)oneConnectionwithmultipleStatements,eachStatementusedbyasinglethreadand(ii)aStatementusedbyonethreadandcancelledbysomeotherthread.Scenario(i),whileitdoeswork,isnotnecessarilyagoodsolutionbecauseitrequiresalotoflockingandwaitingonthesamenetworkconnectionplus(lastbutnotleast)alotofcaching.
^top^
ErrorConditions
WhydoIgetaClassNotFoundErrorwhencallingClass.forName("net.sourceforge.jtds.jdbc.Driver")?
ClassNotFoundErroristhrownbytheclassloaderwhenitcannotfindacertainclass.Inthiscaseitsthenet.sourceforge.jtds.jdbc.Driverclass,whichmeansthatjtds.jarisnotintheclasspath.Ifyouaregettingthisinanapplication,startyourapplicationwith
  1. java-cp<path_to_jtds>/jtds.jar<main_class>
复制代码
Ifyouexperiencethisprobleminaservlet/JSPyouwillhavetoaddjtds.jartoyourwebapplicationsclasspath(e.g.byeditingtheapplicationsweb.xmlfileorbycopyingthejarintotheapplications/servers/libdirectory).
Note:ThenameofthejTDSjarfilemaybejtds-1.1.jarorsomethingsimilar.Ifthatsthecase,replacejtds.jarintheaboveexamplewithjtds-1.1.jarorwhateveryourspecificfilenameis.
^top^
WhydoIgetajava.sql.SQLException:"Nosuitabledriver"whentryingtogetaconnection?
The"Nosuitabledriver"exceptionisthrownbytheDriverManagerwhennoneoftheregisteredDriverimplementationsrecognizesthesuppliedURL.ThismeansthatyoueitherdidnotregisterjTDSwiththeDriverManagerfirst(bycallingClass.forName("net.sourceforge.jtds.jdbc.Driver"))oryoumistypedtheURL(e.g."jbdc:jtds:..."insteadof"jdbc:jtds:...").
Acommonmistakeistoappendasemicolon(";")totheendoftheURL(e.g."jdbc:jtds:sqlserver://server/db;TDS=7.0;"iswrong!).
FormoreinformationaboutURLformatandthepropertiesthatmaybepassedtojTDShavealookatthejTDSURLformat.
^top^
WhydoIgetjava.sql.SQLException:"NetworkerrorIOException:Connectionrefused:connect"whentryingtogetaconnection?
The"Connectionrefused"exceptionisthrownbyjTDSwhenitisunabletoconnecttotheserver.Theremaybeanumberofreasonswhythiscouldhappen:

  • Theservernameismisspelledortheportnumberisincorrect.
  • SQLServerisnotconfiguredtouseTCP/IP.EitherenableTCP/IPfromSQLServersNetworkUtilityapporhavejTDSconnectvianamedpipes(seetheURLformatforinformationonhowtodothis).
  • Thereisafirewallblockingport1433ontheserver.
TocheckwhetherTCP/IPisenabledandtheportisnotblockedyoucanuse"telnet<server_host>1433".Untiltelnetdoesntconnect,jTDSwonteither.Ifyoucantfigureoutwhy,askyournetworkadministratorforhelp.
^top^
Wheredoesoneplaceaninstancenameintheconnectstring?Connectingwith"jdbc:jtds:sqlserver://hostinstance:port/database"givesanSQLExceptionwiththemessage"Logonfailed".
Youwillhavetousetheinstanceproperty(eitherappendittotheURLorplaceitintothePropertiesyousupplytogetConnection)insteadofdoingittheMicrosoftway.Sorry,butjTDS(anditsancestorFreeTDS)existedalongtimebeforenamedinstancessotheURLcouldnotbechanged(andusingitthiswayconfusestheURLparser).
^top^
WhydoIgetajava.sql.SQLException:"UnabletogetinformationfromSQLServer"whentryingtoconnecttoanSQLServerinstance?
Theexceptionyouaregettingisusuallycausedbyatimeout.WhenconnectingtonamedinstancesjTDSneedstoconnectviaUDPtoport1434togetinformationaboutavailableSQLServerinstances.Whiledoingthisittimesout,throwingtheexceptionyousee(whichmeansthatjTDSwasnotabletogetinformationabouttherunninginstances).
Connectiontimeoutsoccurwhenthereisnoserverlisteningontheport(BTW,areyousureyourSQLServerisconfiguredtouseTCP/IPandthatyouactuallyusenamedinstances?).
OnSQLServer2005theSQLBrowserservicemustberunningontheserverhostastheinstancenamelookupportUDP1434ishostedbythisserviceonSQLServer2005ratherthantheSQLServeritself.ThedefaultinstalldoesnotconfiguretheSQLBrowserservicetostartautomaticallysoyoumustdoitmanually.
^top^
Iwashopingthatappending";domain=X"totheURLwouldbeenoughonaworkstationthatwasalreadyloggedintodomainX.WhydoIstillneedtoprovideausernameandpassword?
jTDSisatype4(pureJava)JDBCdriver.Thismeans(amongotherthings)thatitcannotaccessplatform-specificfeatures,suchasdeterminingthecurrentlyloggeduserandhiscredentials.jTDSisdistributedwithanativelibrary(DLL)forSingle-Sign-Onsupport,butthatonlyworksonWindows(pleaseconsultREADME.SSOinthedistributionpackageforinformationonhowtoinstallit).
WithoutthenativeSSOlibraryinstalledyoustillhavetoprovidetheusernameandpasswordbecauseotherwisejTDScannotdetermineusercredentials.Thereisagoodsidetothis:usersonnon-WindowsplatformsareabletologinusingWindowscredentialsbyprovidingthemintheURL,alongwiththedomainname.
^top^
executeQuery()throwsjava.sql.SQLException:"TheexecuteQuerymethodmustreturnaresultset.".
TheJDBCspecandAPIdocumentationforStatementbothstatethatexecuteQuery()isintendedtobeusedwithqueriesthatreturnaResultSet,typicallySELECTstatements.Onthetheotherhand,executeUpdate()isintendedforINSERT,UPDATE,DELETEorDDLstatementsthatreturnupdatecounts.Bothofthese(ResultSetsandupdatecounts)areconsideredbyJDBCtobe"results".ForqueriesthatreturnmultipleresultstheJDBCspecrequiresexecute()tobeused.
Ifyoulllookatthequeryyouaretryingtoexecute,youllseethatitprobablyreturnsanupdatecountfirst,followedbyaResultSet.SoaccordingtotheJDBCspecyoushoulduseexecute()torunit,callgetMoreResults()toskiptheupdatecountandthencallgetResultSet()toobtaintheResultSetyouwant.
Asasidenote,TheMicrosoftdriver(andprobablytheothers,too)"optimize"thisbehaviorbyskippingovertheupdatecount,whichiswrongaccordingtotheJDBCspec.So,formaximumcompatibility,itisrecommendedthatyouuseexecute()anytimeyourunqueriesreturningmorethanoneresulteveniftheparticulardriveryouareusingallowsyoutodootherwise.
ThesamethinghappenswiththeODBCSQLdriverandotherconnectors.Acommonsolutionratherthantheinelegantexecute()andthencyclingthroughmultipleresultsets,istosupresstheupdatecountsforstatementsyouareuninterestedin.Thisiscommonifsayyouarequeryingastoredprocedurethatcreatesatemptable,runsupdatesagainstitandthenreturnsthetableasaresultset.Youcansuppressalltheextra"queryresults"byspecifying"SETNOCOUNTON".
^top^
Igetjava.sql.SQLException:"ResultSetmayonlybeaccessedinaforwarddirection"or"ResultSetisreadonly"whenusingascrollable/updateableResultSet.
Therearethreepossiblecausestothis(ifweexcludenotcreatingtheResultSetwiththeappropriatetypeandconcurrencyinthefirstplace):

  • TheexecutedquerymustbeasingleSELECTstatementoracalltoaprocedurethatconsistsofasingleSELECTstatement(evenaSETorPRINTwillcausetheresultingResultSettobeforwardonlyreadonly).ThisisaSQLServerlimitationandtheresnotmuchjTDScandoaboutit.
  • Thescrollinsensitive/updateablecombinationisnotsupportedbySQLServer,sosuchaResultSetisautomaticallydowngradedtoscrollinsensitive/read-onlybytheserver.Usethescrollsensitive/updateablecombinationanditshouldwork.
  • Theotherpossiblecauseisthatthecursoriskeyset-basedandeitherthetableyouareselectingfromdoesnothaveauniqueprimarykeyorthatprimarykeyisnotincludedinyourSELECT.SeetheSQLServerDocumentationoncursortypesformoreinformation.
InbothcasesifyoucallStatement.getWarnings()rightaftercallingexecuteQuery()youllgetawarningabouttheResultSetbeingdowngraded.Also,pleasetakealookatourResultSetsupportpageforsomeadditionalinformationandtips.
^top^
NotallSQLExceptionsthrownbyjTDSseemtohaveassociatedmeaningfulSQLstatevalues.
Indeed,someSQLExceptionsarereportedwithacorrectstatecodeandsomenot.AstheserveritselfdoesnotreturnanSQLstatecode,theSQLMessageclassassociatesnativeerrornumberswithSQLstatecodes(actuallytheresaverycomprehensivemapthere);SQLServeroriginatederrorsandwarningsthatarenotfoundinthismaparegivenadefaultcodeofS1000,respectively01000.ThisiswhathappenswithSQLServer-returnederrorsandwarningsandisconsistentwithhowotherdrivershandleexceptions.Wehavedoneourbesttomapasmanyerrorsandwarnings,howeverifyoufindsomecaseinwhichotherJDBCorODBCdriversreturnspecificSQLstatesandjTDSdoesntorjTDSreturnedSQLstatesthatareobviouslywrong,pleaseletusknow.Wewillmakethenecessarychanges.
SeetheSQL92specforthecompletelistanddescriptionofSQLstatecodes.
^top^
BatchprocessingusingexecuteBatch()hangsorisunreliableonSybase.
WhenexecutinglargebatchesonSybasetheclientapplicationmayhangortheresponsetimemayvaryconsiderably.Theclientmaybesuspendedifthesystemlogfillssocheckthatthelogspaceissufficientforthebatchyouaretryingtoload.YoucancontroltherealbatchsizeusingthebatchSizeparameter;settingittoanon-zerovaluewillbreakupbatchesintosmallerpiecesonexecution,hopefullyavoidingtheproblem.
Itisalsorecommendedthatyouexecuteeachbatchinatransaction(i.e.withautocommitsettofalse).
^top^
IncorrectBehavior
CallableStatementoutputparametergetterthrowsjava.sql.SQLException:"ParameterXhasnotbeenset.".
Whenexecutingastoredprocedure(oranyquery,forthatmatter)theresponsefromtheSQLServerisserializedinthesameorderitisexecutedin:forstoredproceduresthismeansResultSetsandupdatecountsfirst,outputparametersandreturnvaluelast.jTDSonlycachesupdatecounts,notResultSetsbecausetheycouldeasilycauseOutOfMemoryErrorsoraddimportantperformanceoverheadsifcachedtodisk(theresponsewouldhavetobeparsedtwice,forexample).
Asaconclusion,whenexecutingstoredproceduresthatonlyreturnupdatecountsoutputparameterswillbeavailableimmediately,asjTDSwillprocessandcachethewholeresponse.ButifthestoredprocedurereturnsatleastoneResultSetjTDSwillonlycachetheupdatecountsuptothefirstResultSetandyouwillhavetocallgetMoreResults()toprocessalltheresults.SoforproceduresreturningResultSetsyouwillhavetoloop,consumingallresultsbeforereadingtheoutputparameters(i.e.untilgetMoreResults()returnsfalseANDgetUpdateCount()returns-1).
Incaseyouarewonderingifthisisright,thisisaquotefromtheCallableStatementAPIdocumentation:"Formaximumportability,acallsResultSetobjectsandupdatecountsshouldbeprocessedpriortogettingthevaluesofoutputparameters".Althoughthismeansthata"good"drivercould"fix"thisbehavior,fixingitwouldimplycachingthewholeserverresponse,equalingahugeperformancedrop.
Theexceptionisthrownbecauseitsbettertowarntheuserthattheoutputparametersarenotyetsetinsteadofleavingtheimpressionthatallisokandcauseother,hardertodetectproblems.
^top^
PreparedStatement.executeUpdate()returnsanincorrectupdatecount.
Thisiscausedbytriggers;replicationisalsoimplementedthroughtriggers,soyouwillencounterthisissueonreplicateddatabasestoo.TherootcauseisthattriggersalsoreturnupdatecountsandjTDScantmakethedifferencebetweentheseupdatecountsandthe"real"one(neithercouldanyotherSQLServerclient).However,theupdatecountyouneedisthelastofthem(becausetheactualUPDATE/INSERT/DELETEgetsexecutedonlyafterthetriggers)andthereisluckilyaparameteryoucanspecifyintheURL(ortheconnectionPropertiesorintheDataSource)inorderforjTDStoreturnonlythislastupdatecount(andignoretherestofthem).ThisparameterislastUpdateCountandyoucanfindoutmoreaboutithere.
PleasenotethatsettinglastUpdateCounttotruecouldcauseproblemsifyouusequeriesthatdoactuallyreturnmorethanoneupdatecount(suchasqueriesconsistingofmultipleupdates/inserts),becauseitwillalsoreturnonlythelastoftheseupdatecounts.Althoughqueriesreturningmultipleresultsarenotverycommon,itisthereasonwhythisbehavioriscustomizablefromtheURL.PleasenotethatthisflagonlyaltersthebehaviorofexecuteUpdate();execute()willstillreturnallupdatecounts.
IfyouhavebothqueriesconsistingofmultipleUPDATEs/INSERTs/DELETEsandtriggersyouwontbeabletosetlastUpdateCounttotrueifyouwantalltheupdatecounts,soyouwillhavetoskipovertheirrelevantupdatecountsbycallinggetMoreResults()yourself,whenneeded.
^top^
MemoryUsage
MemoryusagekeepsincreasingwhenusinggeneratedPreparedStatements.
Normally,withaJDBCdriver,PreparedStatementsareprecompiledoncreation,whichgivesincreasedperformanceiftheyareusedasufficientnumberoftimes.jTDStakesthisonestepfurther:whenyoucreateaPreparedStatement,jTDScachesitinternallyandkeepsitthereevenafteryoucloseitsothateverytimeyoucreateitagainitdoesntneedtoberecompiled,itsjustfetchedfromthecache.ThisgivesjTDSa2xperformanceincreaseoverthenextfastestdriverinsome(notsouncommon)cases.Forexample,ifyouhaveamethodthatinsertsarowintoatablebycreatingaPreparedStatement,usingitonceandthenclosingit,yourstatementwillbecompiledonlyonceforeachConnection,nomatterhowmanytimesyoucallthatmethod.
ThenumberofstatementsthatarekeptopensimultaneouslycanbecontrolledwiththemaxStatementsparameter;seethejTDSURLformatformoreinformation.
FutureversionsofjTDSwillallowthetypeofcache(LRU,FIFO,etc)tobeselected.
^top^
TDSProtocolVersion
ImtryingtoconnecttoSQLServer6.5,butithangswhencallinggetConnection().
jTDSusesbydefaultTDS8.0(whichisSQLServer2000sprotocol)tocommunicatewiththedatabaseserver.WhenjTDSsendsthe8.0loginrequestSQLServer6.5doesntunderstanditsoitreturnsa4.2error(Loginfailed).ButbecausejTDSisexpectingaTDS8.0packetasaresponse(notaTDS4.2packet)itdoesntproperlyunderstandtheresponsepacketandithangswaitingformoredatafromtheserver.Thesolutionistosetthe"TDS"propertyto"4.2"(throughtheURLorPropertiesobjectpassedtogetConnection()orusingtheappropriatesetterofTdsDataSource,ifyouareusingtheTdsDataSource).
FormoreinformationaboutURLformatandthepropertiesthatmaybepassedtojTDShavealookatthejTDSURLformat.
^top^
Whydocolumnnamesmorethan30characterslong,getchoppedoffat30characters?
YouareveryprobablyusingTDS4.2tocommunicatewiththeSQLServer.TDS4.2istheprotocolusedbySQLServer6.5andithasthelimitationsofSQLServer6.5(amongwhichamaximumcolumnnamesizeof30characters).jTDS0.2andearlieruseTDS4.2bydefault.InordertochangethatyouhavetospecifyitexplicitlyinthePropertiesortheURLyousupplywhenyoucreatetheconnection.Ifyouexperiencethisproblemwithversions0.3orlater,thenyouhavespecified(intheconnectionpropertiesorURL)thatTDS4.2shouldbeused;removethatsetting.
FormoreinformationaboutURLformatandthepropertiesthatmaybepassedtojTDShavealookatthejTDSURLformat.
^top^
jTDSfetchesonlythefirst4KbofIMAGEdata.
YouareveryprobablyusingTDS4.2tocommunicatewiththeSQLServer.TDS4.2istheprotocolusedbySQLServer6.5andithasthelimitationsofSQLServer6.5(amongwhichamaximumsizeforIMAGEdataof4Kb).jTDS0.2andearlieruseTDS4.2bydefault.InordertochangethatyouhavetospecifyitexplicitlyinthePropertiesortheURLyousupplywhenyoucreatetheconnection.Ifyouexperiencethisproblemwithversions0.3orlater,thenyouhavespecified(intheconnectionpropertiesorURL)thatTDS4.2shouldbeused;removethatsetting.
FormoreinformationaboutURLformatandthepropertiesthatmaybepassedtojTDShavealookatthejTDSURLformat.
^top^
Technicalsupport
IsthereanycommercialtechnicalsupportavailableforjTDS?
ForthemomentyoucangetofficialtechnicalsupportfromindividualdevelopersofjTDS;contactanyofusandwellbehappytoprovideyouwithourtechsupporttermsandconditions.Ofcourse,wewillkeepofferingsupportonourSourceForgeforumsjustaswediduntilnow;weareonlytryingtoencourageadoptionofjTDS,notmakeafortuneoutofit.
Asforwherethetechnicalsupportmoneywillgo,partofthemwillberetainedbythedeveloperandpartofthemwillgobackintojTDS.CurrentlytheaimistoraiseUS$2000,topayforJDBCcertification.Were100%surejTDSwillpassthecertificationtestsuite,wejustneedthemoneyforit.Tothisend,wealsoacceptdonations.
^top^
Other
IdidntfindtheanswertomyprobleminthisFAQ.WhatshouldIdo?
IfyouneedhelpwithanyotherjTDS-relatedissue,searchtheHelpforumfirstandifyoustilldontfindanything,postaquestion.Itwillusuallygetansweredwithin24hours.Onething,though:pleaseregisterasaSourceForgememberandloginifyouhaventdonesoyet,soyoucanbeautomaticallynotifiedofupdatestothequestionsyoupost.
Ifyouencounteredanissuethatyouhavetestedandretestedandyouresureitsabug,usetheBugslinkontopofthepage.Again,makesureyouareaSourceForgememberANDthatyouareloggedinwhenyoupost.


Java到底会发战成什么样,让我们拭目以待吧,我始终坚信着java会更好。以上都是俺个人看法,欢迎大家一起交流.
谁可相欹 该用户已被删除
沙发
发表于 2015-1-21 12:23:39 | 只看该作者
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
深爱那片海 该用户已被删除
板凳
发表于 2015-1-30 18:09:38 | 只看该作者
那么我书也看了,程序也做了,别人问我的问题我都能解决了,是不是就成为高手了呢?当然没那么简单,这只是万里长征走完了第一步。不信?那你出去接一个项目,你知道怎么下手吗,你知道怎么设计吗,你知道怎么组织人员进行开发吗?你现在脑子里除了一些散乱的代码之外,可能再没有别的东西了吧!
金色的骷髅 该用户已被删除
地板
发表于 2015-1-31 20:23:26 | 只看该作者
一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从
灵魂腐蚀 该用户已被删除
5#
发表于 2015-1-31 21:58:29 | 只看该作者
Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。
海妖 该用户已被删除
6#
发表于 2015-2-4 14:12:31 | 只看该作者
Java语言支持Internet应用的开发,在基本的Java应用编程接口中有一个网络应用编程接口(java net),它提供了用于网络应用编程的类库,包括URL、URLConnection、Socket、ServerSocket等。Java的RMI(远程方法激活)机制也是开发分布式应用的重要手段。
小魔女 该用户已被删除
7#
发表于 2015-2-8 19:36:53 | 只看该作者
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
小妖女 该用户已被删除
8#
发表于 2015-2-25 22:51:00 | 只看该作者
如果你学过HTML,那么事情要好办的多,如果没有,那你快去补一补HTML基础吧。其实JSP中的Java语法也不多,它更象一个脚本语言,有点象ASP。
兰色精灵 该用户已被删除
9#
发表于 2015-2-26 06:29:32 | 只看该作者
J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。
因胸联盟 该用户已被删除
10#
发表于 2015-3-3 06:49:21 | 只看该作者
Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。
精灵巫婆 该用户已被删除
11#
发表于 2015-3-4 10:48:22 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
只想知道 该用户已被删除
12#
发表于 2015-3-9 15:05:31 | 只看该作者
如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。
小女巫 该用户已被删除
13#
发表于 2015-3-11 03:43:35 | 只看该作者
Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。
山那边是海 该用户已被删除
14#
发表于 2015-3-17 19:39:48 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
分手快乐 该用户已被删除
15#
发表于 2015-3-24 21:54:21 | 只看该作者
当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢?
冷月葬花魂 该用户已被删除
16#
发表于 2015-3-28 17:35:40 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
愤怒的大鸟 该用户已被删除
17#
发表于 2015-4-2 22:20:05 | 只看该作者
另外编写和运行Java程序需要JDK(包括JRE),在sun的官方网站上有下载,thinking in java第三版用的JDK版本是1.4,现在流行的版本1.5(sun称作J2SE 5.0,汗),不过听说Bruce的TIJ第四版国外已经出来了,是专门为J2SE 5.0而写的。
若相依 该用户已被删除
18#
发表于 2015-4-8 22:24:09 | 只看该作者
你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。
莫相离 该用户已被删除
19#
发表于 2015-4-11 15:12:46 | 只看该作者
设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧
简单生活 该用户已被删除
20#
发表于 2015-4-21 01:52:44 | 只看该作者
接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-12-23 07:24

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表