Created
September 26, 2017 13:50
-
-
Save ninjarobot/b8155d6b3562876c946f9adf6a7931e9 to your computer and use it in GitHub Desktop.
Run a query against PostgreSQL with F# using the Npgsql driver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async { | |
use conn = new NpgsqlConnection (connectionString) | |
use cmd = conn.CreateCommand (CommandText="SELECT field1, field5 FROM some_table WHERE foo=:bar") | |
cmd.Parameters.AddWithValue ("bar", "baz) |> ignore | |
do! conn.OpenAsync () |> Async.AwaitTask // Automatically closed when disposed | |
use! reader = cmd.ExecuteReaderAsync() |> Async.AwaitTask | |
// Need a function to iterate through results | |
let rec readData results = async { | |
let! hasRecord = reader.ReadAsync () |> Async.AwaitTask | |
match hasRecord with | |
| true -> | |
let field1 = reader.GetString 0 // 0-based index of selected fields | |
let field5 = reader.GetString 1 | |
return! readData ((field1, field5) :: results) | |
| false -> return results |> List.rev // end of reader, so reverse list and return | |
} | |
// Now pass an empty list to that function | |
return! List.empty |> readData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment