F#连接到在线MySQL数据库执行查询

时间:2016-05-24 13:24:36

标签: mysql sql database f# connect

我正在制作一个F#项目,需要对在线mysql数据库进行一些数据库查询。谁能帮帮我吗。我需要这样的东西

    \\  Connect to DB
    let servername = "localhost"
    let username = "username"
    let password = "password"
    \\ Code that connects to db
    \\ Print error message if can connect 

    \\ Query 
    let query = "SELECT * FROM table ..."
    \\ Code that executes query 
    \\ Error Message if query not executed  

2 个答案:

答案 0 :(得分:3)

您应该安装MySQL的.NET驱动程序。然后安装SQLprovider。文档中有MySQL的示例。您将连接到数据库并查询它:

type sql = SqlDataProvider<
                dbVendor,
                connString,
                ResolutionPath = resPath,
                IndividualsAmount = indivAmount,
                UseOptionTypes = useOptTypes,
                Owner = "HR"
            >
let ctx = sql.GetDataContext()

let employees = 
    ctx.Hr.Employees 
    |> Seq.map (fun e -> e.ColumnValues |> Seq.toList)
    |> Seq.toList

connstring将是这样的:

[<Literal>]
let connString  = "Server=localhost;Database=HR;User=root;Password=password"

您还应该阅读https://msdn.microsoft.com/visualfsharpdocs/conceptual/walkthrough-accessing-a-sql-database-by-using-type-providers-%5bfsharp%5d

答案 1 :(得分:1)

我还要说SQLProvider是可行的方法,因为您可以根据数据库验证逻辑,并注意数据库是否发生了变化。

但如果您愿意,可以手动连接:

// Reference Nuget package MySql.Data
//#r @"./../packages/MySql.Data/lib/net40/MySql.Data.dll"

open System
open MySql.Data.MySqlClient

let cstr = "server = localhost; database = myDatabase; uid = username;pwd = password"

let ExecuteSqlAsync (query : string) parameters =
  use rawSqlConnection = new MySqlConnection(cstr)
  async {
    do! rawSqlConnection.OpenAsync() |> Async.AwaitIAsyncResult |> Async.Ignore
    use command = new MySqlCommand(query, rawSqlConnection)
    parameters |> List.iter(fun (par:string*string) -> command.Parameters.AddWithValue(par) |> ignore)
    let! affectedRows = command.ExecuteNonQueryAsync() |> Async.AwaitTask
    match affectedRows with
    | 0 -> "ExecuteSql 0 rows affected: " + query |> Console.WriteLine
           ()
    | x -> ()
  }

let ExecuteSql (query : string) parameters =
    use rawSqlConnection = new MySqlConnection(cstr)
    rawSqlConnection.Open()
    use command = new MySqlCommand(query, rawSqlConnection)
    parameters |> List.iter(fun (par:string*string) -> command.Parameters.AddWithValue(par) |> ignore)
    let affectedRows = command.ExecuteNonQuery()
    match affectedRows with
    | 0 -> "ExecuteSql 0 rows affected: " + query |> Console.WriteLine
           ()
    | x -> ()