alancc
alancc

Reputation: 799

Create Access Database in Visual C++

Currently I need to find a method to create an Access database in Visual C++ 2008, so that:

  1. I can create the Access database in different formats, including Access 95/97 format, 2000 format, and 2007 accdb format.
  2. I can create not only tables, but also other objects, including queries, reports, forms and macros in the Access database.
  3. When adding a large volume of records into the tables, the method has a better performance.

I have searched online, and have found resourced such as this which lists some methods, however, as far as I know, DAO seems to be deprecated.

How about the other methods?

Thanks

Upvotes: 1

Views: 1222

Answers (1)

Van Ng
Van Ng

Reputation: 803

As I have understood, you want to create database, objects in it, via calling some function and procedures. Best approach to my mind is to use DAO Library. Here is VBScript example:

Sub CreateDatabaseFile(ByVal strDbPath) 
    Dim wspDefault 'As Workspace
    Dim dbs      ' As Database
    Dim dbEngine ' DAO DB Engine    
    Dim dbLangGeneral
    dbLangGeneral = ";LANGID=0x0409;CP=1252;COUNTRY=0"
    Set dbEngine = CreateObject("DAO.DBEngine.120")
    Set wspDefault = DBEngine.Workspaces(0)
    Set dbs = wspDefault.CreateDatabase(strDbPath, dbLangGeneral)
    Dim s
    s="CREATE TABLE tblCustomers (CustomerID INTEGER CONSTRAINT PK_tblCustomers PRIMARY KEY, " _
    & " [Last Name] TEXT(50) NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50), " _
    & " Address TEXT(40)) "
    dbs.execute s
    dbs.Close

    Dim AccessApp
    Set AccessApp = CreateObject("Access.Application")
    AccessApp.OpenCurrentDatabase strDbPath
    Dim frm 'As Form
    Dim ctlLabel 'As Control
    Dim  ctlText 'As Control
    Dim intDataX 'As Integer, intDataY As Integer
    Dim intDataY
    Dim intLabelX 'As Integer, intLabelY As Integer
    Dim intLabelY

    ' Create new form with tblCustomers table as its record source.
    Set frm = AccessApp.CreateForm
    'frm.Name = "MyForm"
    frm.RecordSource = "tblCustomers"

    ' Set positioning values for new controls.
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100

    ' Create unbound default-size text box in detail section.
    Dim acTextBox
    acTextBox = 109
    Set ctlText = AccessApp.CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ctlText.ControlSource = "Last Name"
    Dim acLabel
    acLabel = 100
    ' Create child label control for text box.
    Set ctlLabel = AccessApp.CreateControl(frm.Name, acLabel, , _
         ctlText.Name, "NewLabel", intLabelX, intLabelY)
    Dim acButton

    AccessApp.DoCmd.Save, frm.Name
    ' Restore form.
    AccessApp.DoCmd.Restore
    AccessApp.DoCmd.Quit
End Sub
Call CreateDatabaseFile("c:\test\a test database file.mdb")

Upvotes: 1

Related Questions