F#连接到联机MySQL DB执行查询

qoefvg9y  于 2023-05-16  发布在  Mysql
关注(0)|答案(2)|浏览(141)

我正在做一个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
w6lpcovy

w6lpcovy1#

您应该安装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

plicqrtu

plicqrtu2#

我也会说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 -> ()

相关问题