You are on page 1of 2

Creating a Database Programmatically

Please note: The only use I can imagine for this is if you’ve tested to see if the database
exists and it doesn’t – which in itself, suggests something is wrong. I would usually
expect the database to be designed and created prior to use of the program, since you
don’t want multiple copies of the database and this code won’t work once the database
exists.

This code was based on code found @: www.freevbcode.com

Private Function CreateAccessDatabase(ByVal DatabaseFullPath As String)


As Boolean
Dim blnSuccess As Boolean
Try
'Make sure the folder
'provided in the path exists. If file name w/o path
'is specified, the database will be created in your
'application folder.

mstrCreateTable = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=" & DatabaseFullPath
adoxCat.Create(mstrCreateTable)

'name table, append fields to table


adoxTable.Name = "Witnesses"
adoxTable.Columns.Append("LastName",
ADOX.DataTypeEnum.adVarWChar, 40)
adoxTable.Columns.Append("FirstName",
ADOX.DataTypeEnum.adVarWChar, 20)
adoxTable.Columns.Append("Age", ADOX.DataTypeEnum.adInteger)

'append tables to database


adoxCat.Tables.Append(adoxTable)

'internal index on two fields


adoxIndex.Name = "TwoColumnsIndex" 'name of index
adoxIndex.Columns.Append("LastName")
adoxIndex.Columns.Append("Age")

adoxTable.Indexes.Append(adoxIndex)
blnSuccess = True

Catch Excep As System.Runtime.InteropServices.COMException


blnSuccess = False
'do whatever else you need to do here, log,
'msgbox etc.
Finally
adoxCat = Nothing
End Try
Return blnSuccess
End Function

Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles btnCreateDatabase.Click
'Call the function and test to see if it’s been created.
If CreateAccessDatabase(Application.StartupPath &
"\Identikit.mdb") = True Then
MsgBox("Database Created")
Else
MsgBox("Database Creation Failed")
End If
End Sub

You might also like