Nov 092009

This is a very straightforward port of SQL Azure code from msdn:

#r "System.Core"

open System
open System.Collections.Generic
open System.Linq
open System.Text
open System.Data.SqlClient
open System.Data

// Provide the following information
let userName = "<ProvideUserName>"
let password = "<ProvidePassword>"
let dataSource= "<ProvideServerName>"
let sampleDatabaseName = "<ProvideDatabaseName>"

let sendToCommand() (command:SqlCommand) query =
    command.CommandText <- query
    command.ExecuteNonQuery()

// create the sample database
let createDatabase (command:SqlCommand) =
    (String.Format("CREATE DATABASE {0}", sampleDatabaseName)) |> sendToCommand() command |> ignore

// perform various operations
let modifyDatabase (command:SqlCommand) =
    let send() = sendToCommand() command
    // Create a table
    "CREATE TABLE T1(Col1 int primary key, Col2 varchar(20))" |> send() |> ignore

    // Insert sample records
    let rowsAdded = "INSERT INTO T1 (col1, col2) values (1, 'string 1'), (2, 'string 2'), (3, 'string 3')" |> send()

    // Query the table and print the results
    let readCols() =
        command.CommandText <- "SELECT * FROM T1"
        use reader = command.ExecuteReader()
        // Loop over the results
        while reader.Read() do
            Console.WriteLine("Col1: {0}, Col2: {1}", reader.["Col1"].ToString().Trim(), reader.["Col2"].ToString().Trim())

    // Query the table and print the results
    readCols()

    // Update a record
    "UPDATE T1 SET Col2='string 1111' WHERE Col1=1" |> send() |> ignore

    //Delete a record
    "DELETE FROM T1 WHERE Col1=2" |> send() |> ignore

    Console.WriteLine("\nAfter update/delete the table has these records...")

    // Query the table and print the results
    readCols()

let sqlBuild initialCatalog =
    new SqlConnectionStringBuilder(
         DataSource = dataSource,
         InitialCatalog = initialCatalog,
         Encrypt = true,
         TrustServerCertificate = false,
         UserID = userName,
         Password = password
    )

let runQuery stringBuilder func =
    use conn = new SqlConnection(stringBuilder.ToString())
    use command = conn.CreateCommand()
    conn.Open()
    func(command)
    conn.Close()

// Create a connection string for the master database, connect to the master database and create the sample database
createDatabase |> ("master" |> sqlBuild |> runQuery)
// Create a connection string for the sample database, connect to the sample database and perform various operations
modifyDatabase |> (sampleDatabaseName |> sqlBuild |> runQuery)
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • RSS
  • StumbleUpon
  • Twitter
Posted by Matt Tagged with: ,

Leave a Reply

(required)

(required)