• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 137
  • Last Modified:

Creating DB through code

I am learning VB on my own and I came across a book that gives a modified example(pseudo code) on how to create a database in Vb using code to create it.  I have the professional edition of VB 5.0 and would be greatly appreciative if someone could give me the code to create a database with one table and one fld w/in that table.  This is work related and it would be helpful.  I can only find pseudo code in books.  I need  help.
0
timpeters
Asked:
timpeters
1 Solution
 
yronnenCommented:
First, go to the reference menu in the VB enviorment and add a reference to Microsoft DAO 3.5 library.

This code will create a database with one table, two fields and a primary key:

sub createDB()
Dim DB As Database
Dim TBL As TableDef
Dim FLD1 As Field
Dim FLD2 As Field
Dim IDX As Index

DBEngine.DefaultType = dbUseJet
Set DB = DBEngine.Workspaces(0).CreateDatabase("c:\mydb.mdb", dbLangGeneral)
Set TBL = DB.CreateTableDef("MyTable")
Set FLD1 = TBL.CreateField("Field1", dbInteger)
Set FLD2 = TBL.CreateField("Fields2", dbText, 20)
TBL.Fields.Append FLD1
TBL.Fields.Append FLD2
Set IDX = TBL.CreateIndex("Prime")
IDX.Primary = True
Set FLD1 = IDX.CreateField("Field1", dbInteger)
IDX.Fields.Append FLD1
TBL.Indexes.Append IDX
DB.TableDefs.Append TBL
DB.Close
end sub

If you know some SQL, you can use a shorter procedure (this one does exactly the same):

sub CreateDBSQL()
dim DB as database
dim SQL as string

DBEngine.DefaultType = dbUseJet
Set DB = DBEngine.Workspaces(0).CreateDatabase("c:\mydb.mdb", dbLangGeneral)
SQL="CREATE TABLE NewTable (Field2 TEXT 20,  "Field1  INTEGER CONSTRAINT Prime PRIMARY KEY)"
db.execute sql
db.close
end sub
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now