|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
我见过java运行在手机上,包括很廉价的山寨手机,但是却暂时没发现.net在手机上有什么作为。wp7可能是个转机,但是按照《Java的跨平台就是一句谎言。那.net的跨平台也当之无愧是一句谎言。Question:
WhenIminsertingblankvalueintoaSQLServerdatabase,foraDateTimecolumn,mydatabaseitisinserting1/1/1900evenifIassignNulltothevariableinmyapplication.Hereisanexample:
stringxx=null;
//T-SQL="INSERTINTOtempTable(DateTimeColumn)VALUES(xx);"
Canyouhelpmewiththisproblem?
Thanks®ards,
Ravi
Answer:
Ravi,youreinluck.Thisisactuallyaneasyfix-youjusthavetoknowwhattodo(andunfortunatelysometimesfindingtherightthingtodoishalfthebattle).
Whenyouareinsertingdataintoadatabase,theADO.NETdataprovidersandyourdatabasemaydistinguishbetweenanullobjectandanuninitializedvalue.Inyourcase,insertinganullintoaDateTimecolumncausesthedatabasetoseedthefieldwiththedefaultinitializedvalue-1/1/1900.Inrealityyouwanttotellthedatabasethatthefieldinquestionshouldremainuninitialized.Todothatthereisasingletonclassinthe.NETFrameworkthatisdesignedforpassingtoadatabasetorepresentanuninitializedvalue.ThatclassisSystem.DBNull;andspecificallytheValuepropertyoftheclass.
Toinsertarecordintoyourdatabase,andmaintaintheuninitializedstateoftheDateTimefieldsyouwoulddosomethinglikethis:
[C#]
SqlCommandcmd=newSqlCommand();
cmd.Connection=con;
cmd.CommandText="INSERTINTOmyTable(Name,RegisteredDate,CancelDate)"+
"VALUES(@Name,@RegisteredDate,@CancelDate)";
cmd.Parameters.Add("@Name","DougSeven");
cmd.Parameters.Add("@RegisteredDate",DateTime.Today);
//UseSystem.DBNull.Valuetoleavethefielduninitialized
cmd.Parameters.Add("@CancelDate",System.DBNull.Value);
[VisualBasic.NET]
DimcmdAsNewSqlCommand()
cmd.Connection=con
cmd.CommandText="INSERTINTOmyTable(Name,RegisteredDate,CancelDate)"&_
"VALUES(@Name,@RegisteredDate,@CancelDate)"
cmd.Parameters.Add("@Name","DougSeven")
cmd.Parameters.Add("@RegisteredDate",DateTime.Today)
UseSystem.DBNull.Valuetoleavethefielduninitialized
cmd.Parameters.Add("@CancelDate",System.DBNull.Value)
InmanycasesIwillactuallyperformchecksonthevaluepassedtomyinsertorupdateoperationtodetermineifDBNull.ValueshouldbesenttothestoredprocedureIaminvoking.IfyouweretospendsometimelookingatthecodeIwriteintherealworld,youwouldseesomethinglikethis(thisiscodedirectfromaclientapplication):
Ifuser.FirstName=String.EmptyThen
cmd.Parameters("@FirstName").Value=System.DBNull.Value
Else
cmd.Parameters("@FirstName").Value=user.FirstName
EndIf
Ifuser.LastName=String.EmptyThen
cmd.Parameters("@LastName").Value=System.DBNull.Value
Else
cmd.Parameters("@LastName").Value=user.LastName
EndIf
Ifuser.RegisteredDate=NothingThen
cmd.Parameters("@RegisteredDate").Value=System.DBNull.Value
Else
cmd.Parameters("@RegisteredDate").Value=user.RegisteredDate
EndIf
Summary
Tosetvaluesinadatabasetotheiruninitializedstate,usetheSystem.DBNull.Valuestructure.YoucanpassthisvalueinusingaT-SQLcommand,orastoredprocedure-passingDBNull.Valueasaparameter.
其实Java之所以在曾经独步天下,就是因为他的跨平台、安全性,这两方面,效率可不是Java的强项,反而是他最短的一块挡板,虽然net总是用理论证明比.NET快。 |
|