let sqlStatement = "select top 1 * from OrderList where State like @state"
using(defaultDB.GetSqlStringCommand(sqlStatement))(fun sqlCmd ->
defaultDB.AddInParameter(sqlCmd, "state", DbType.String, "New York")
using(defaultDB.ExecuteReader(sqlCmd))(fun sqlReader ->
DisplayRowValue sqlReader))
存储过程带参数
using(defaultDB.GetStoredProcCommand("ListOrdersByState"))(fun sprocCmd ->
defaultDB.AddInParameter(sprocCmd, "state", DbType.String, "New York")
using(defaultDB.ExecuteReader(sprocCmd))(fun sprocReader ->
DisplayRowValue sprocReader))
2.对象映射
type Product() =
member val ID:int=0 with get, set
member val Name:string="" with get, set
member val Description:string="" with get, set
let productData = defaultDB.ExecuteSprocAccessor<Product>("GetProductList", [|box "%bike%"|])
let result = query{
for productItem in productData do
where (productItem.Description <> null)
sortBy productItem.Name
select productItem
}
result |> Seq.iter (fun i -> printfn "Product Name:%A\nDescription:%A\n" i.Name i.Description)
let sqlproduct = defaultDB.ExecuteSqlStringAccessor<Product>("select * from Products")
query{
for productItem in sqlproduct do
where (productItem.Description <> null)
sortBy productItem.Name
select productItem
} |> Seq.iter (fun i -> printfn "id:%A\nProduct Name:%A\nDescription:%A\n" i.ID i.Name i.Description)
3.获得XML结果
let sqlserverDB = factory.Create("ExampleDatabase") :?> SqlDatabase
using(sqlserverDB.GetSqlStringCommand("select * from OrderList where State = @state for xml auto"))(fun xmlCmd->
xmlCmd.Parameters.Add(new SqlParameter("state", "Colorado")) |> ignore
using(sqlserverDB.ExecuteXmlReader(xmlCmd))(fun reader ->
while not reader.EOF do
if reader.IsStartElement() then
Console.WriteLine(reader.ReadOuterXml())))
<OrderList Id="1" Status="DRAFT" CreatedOn="2009-02-01T11:12:06" Name="Adjustable Race" LastName="Abbas" FirstName="Syed" ShipStreet="123 Elm Street" ShipCity="Denver" ShipZipCode="12345" ShippingOption="Two-day shipping" State="Colorado" />
<OrderList Id="2" Status="DRAFT" CreatedOn="2009-02-03T01:12:06" Name="All-Purpose Bike Stand" LastName="Abel" FirstName="Catherine" ShipStreet="321 Cedar Court" ShipCity="Denver" ShipZipCode="12345" ShippingOption="One-day shipping" State="Colorado" />
如果要以XML文件的形式使用的话要再加一个根节点。
4.获得单个结果 using(defaultDB.GetSqlStringCommand("select [Name] from States"))(fun sqlCmd ->
printfn "%A" (defaultDB.ExecuteScalar(sqlCmd).ToString()))
<add name="AsyncExampleDatabase" connectionString="Data Source=(localdb)\v11.0;<span style="color:#000099;">Asynchronous Processing=true;</span>AttachDbFilename=E:\WorkHell\fsharp-practise\EnterpriseLibraryPractise\DataAccessExamples.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
注意Asynchronous Processing = true
let asyncDB = factory.Create("AsyncExampleDatabase")
let AsyncGetDBInfo (db:Database) =
using(new ManualResetEvent(false))(fun doneWaitingEvent ->
using (new ManualResetEvent(false))(fun readCompleteEvent->
try
let cmd = db.GetStoredProcCommand("ListOrdersSlowly")
db.AddInParameter(cmd, "state", DbType.String, "Colorado")
db.AddInParameter(cmd, "status", DbType.String, "DRAFT")
db.BeginExecuteReader(cmd, (fun asyncResult ->
doneWaitingEvent.Set() |> ignore
try
try
using(db.EndExecuteReader(asyncResult))(fun reader ->
DisplayRowValue(reader)
)
with
| ex -> printfn "Error afer data access completed: %A" ex.Message
finally
readCompleteEvent.Set() |> ignore
), null) |> ignore
while not (doneWaitingEvent.WaitOne(1000)) do
Console.Write "Waiting ..."
readCompleteEvent.WaitOne() |> ignore
with
| ex -> printfn "Error while starting data access :%A" ex.Message
))
AsyncGetDBInfo asyncDB
异步的begin end被分开执行,还要注意设置一个ManualResetEvent。看着就头大。
接下来是使用Task模式 let DoReadDataAsyncronouslyTask (db:Database) = async{
try
let cmd = db.GetStoredProcCommand("ListOrdersSlowly")
db.AddInParameter(cmd, "state", DbType.String, "Colorado")
db.AddInParameter(cmd, "status", DbType.String, "DRAFT")
use timer = new Timer(fun _ -> printf "Waiting...")
timer.Change(0, 1000) |> ignore
use! reader = Async.FromBeginEnd(cmd,
(fun (cmd:DbCommand,callback,state) -> db.BeginExecuteReader(cmd, callback, state)),
db.EndExecuteReader)
timer.Change(Timeout.Infinite, Timeout.Infinite)|>ignore
printf "\n\n"
DisplayRowValue reader
with
| ex -> printfn "Error while starting data access: %A" ex.Message
}
let DoReadAccessorDataAsyncronouslyTask (db:Database) = async{
try
let accessor = db.CreateSprocAccessor<Product>("GetProductsSlowly")
use timer = new Timer(fun _ -> printf "Waiting...")
timer.Change(0, 1000) |> ignore
let! productData = Async.FromBeginEnd((fun (callback,state) -> accessor.BeginExecute(callback, state, [|(box "%bike%");(box 20)|])),
accessor.EndExecute)
timer.Change(Timeout.Infinite, Timeout.Infinite)|>ignore
printfn ""
let result = query{
for productItem in productData do
where (productItem.Description <> null)
sortBy productItem.Name
select productItem
}
productData |> Seq.iter (fun i -> printfn "Product Name:%A\nDescription:%A\n" i.Name i.Description)
printf "\n\n"
with
| ex -> printfn "Error while starting data access: %A" ex.Message
}
DoReadAccessorDataAsyncronouslyTask(asyncDB) |> Async.RunSynchronously
defaultDB.ExecuteNonQuery(cmd) |> ignore