Search code examples
vb.netvisual-studio-2010ms-accessms-access-2007

How to generate a new MS access file programmatically


I have looked far and wide, in the deepest darkest corners of the internet, but for the life of me, I can not find the correct way to open a NEW Access file and then using vb.net to write data in the database..

The keywords here are NEW database, I don't want to open an existing file.

Is this even possible?

Thanks in advance!


Solution

  • I have finally found the way, thanks to a co-worker of mine

    Neither ADO.NET nor ActiveX Data Object (ADO) provides the means to create Microsoft Access Database. However, we can create Access databases by using the Microsoft Jet OLE DB Provider and Microsoft ADO Ext. 2.7 for DDL and Security (ADOX) with the COM Interop layer. To do so, select References from the Project Menu, choose the COM tab, and add a reference to Microsoft ADO Ext. 2.7 for DDL and Security; then you can use this function.

    When you have done this, use the following snippet to create a database


    Public Class Form1
    
        Private Sub btnLoad_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnLoad.Click
    
            CreateAccessDatabase("C:\test\testDB.mdb")
            MsgBox("Database created")
        End Sub
    

        Public Function CreateAccessDatabase( ByVal DatabaseFullPath As String) As Boolean
            Dim bAns As Boolean
            Dim cat As New ADOX.Catalog()
            Try
    
                Dim sCreateString As String
                sCreateString =_ 
                               "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
                               DatabaseFullPath
                cat.Create(sCreateString)
    
                 bAns = True
    
            Catch Excep As System.Runtime.InteropServices.COMException
                 bAns = False
    
            Finally
                cat = Nothing
            End Try
            Return bAns
        End Function
    End Class