Tuesday, May 3, 2011

F# and ADO.NET to Connect To Access 2007

I am very new to F#, and I was trying to find the simplest way to connect to Access 2007 using System.Data.OleDb. I have done this with C#, but I cannot figure out how to convert the syntax to F#. The following is what I know so far:

#light
open System.Windows.Forms
open System.Data.OleDb
open System.Data

let ADOCon = new OleDbConnection()
let DTab = new DataTable()

ADOCon.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\...mdb"

I know the syntax for the connection string is wrong, and I cannot figure out how to add an OleDataAdapter and OleCommandBuilder. Does anyone know a straight forward example starting from #light to open connection? Thank you, in advance!

From stackoverflow
  • If you show the corresponding C# it may help.

    Assuming you are trying to assign a property on the last line, then you want "<-":

    ADOCon.ConnectionString <- "yadda"
    
  • This is so NOT the F# way to do things, but this works ...

    open System.Data  
    open System.Data.OleDb
    
    let cmd = new OleDbCommand( "SELECT * FROM TABLE1" );
    let conn = new OleDbConnection( @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Database1.mdb;Persist Security Info=False;" )
    
    conn.Open();
    cmd.Connection <- conn;
      using (cmd.ExecuteReader()) 
        (fun reader ->
          if (reader.HasRows) then
            (
              printfn "Queried: %s" cmd.CommandText
              while (reader.Read()) do
                (
                  let id = reader.GetInt32(0)
                  let tmp = reader.GetString(1)
    
                  printfn "%d %s" id tmp
                )
              done
            )
          else (printfn "Empty result")
          )
    
    conn.Close();
    ;;
    
  • I finally compiled some code to to read an Access 2007 Db in F# from a winform:

    open System.Data.OleDb
    open System.Data
    
    //Create winform//
    let frmMain = new Form()
    
    //Connect to Access Db//
    let ADOCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
      Data Source=C:\Users\...\Desktop\FSharpDb.mdb")
    
    let DAdapter = new OleDbDataAdapter("Select * from Names_Table", ADOCon)
    
    let DTable = new DataTable()
    DAdapter.Fill(DTable)|>ignore
    let view = new DataGridView()
    do view.DataSource <- DTable
    
    let ConnectionString = 
        ADOCon.Open()
    
    frmMain.Controls.Add(view)
    
    //Run main form on start up
    Application.Run(frmMain)
    

    Thank you for all who helped!

0 comments:

Post a Comment