Working With Databases II
There will come a time when you may need to make changes to your application. Or you want to add new features to your application. Either way you may need to make changes to your database. When you do this you can no long just provide a patch to update your software, the customer has to install the full version of your software and some how get their data out of the old database in to the new one.
That's where this tutorial comes in. I will be providing examples and code that will allow you to either, export your customers data from the old database and import it in to the new one, or use code to alter the database. Either way it will give your customer an alternative to manually re-entering the data in to the new database. Which believe me, will make your customers very happy.
I will be using VB5/6 and Access 97 to test all the code examples for this tutorial. If you haven't done so you might want to take a look at the Hands On project "Working with Databases" that I posted a few months back. You should also note that the syntax for your database my very so check you database manual for the proper syntax for your database. I will however try when ever possible to us code that will work on all databases, but sometimes that is not possible.
We will be using DML (The Data Manipulation Language) to retrieve, insert and modify database information. These commands will be used by all database users during the routine operation of the database.
First up Exporting
Exporting Data I
When changing the underling structure of a database you have two choices, actually three. One provide your customer with the option to export the data from the old database to the new one. Two, alter the existing database so the customer has doesn't have to do anything. The third I wouldn't recommend, have your customer manually re-enter all the records in the new database.
We will first look a exporting data out of the current database. There are several ways to do this, you can pick the one that most matches your situation. This can be done using DAO or ADO and most of these examples can be applied to any database. When ever possible I will your standard SQL syntax.
The first example I will use DAO to export records out of a database in to a comma delimited file. A comma delimited file is a text file that separates the records by using a comma, each comma represents a new record. The file is then saved in a directory that you specify and can then later be imported in to a different database.
This example uses the SQL INTO method to copy the records out of a database and save them to a csv(Comma Separated Variable)file.
Public Sub Main()
Exporting Data II
Private Sub ExportDB()Exporting Data III
Private Sub ADOExport()
Dim oCn As New ADODB.Connection
Dim oRs As New ADODB.Recordset
'This is the connection to the database. This used MS SQL server but it can
'be any database.
oCn.Open "provider=sqloledb;data source=(local);user id=me;initial
catalog=northwind;"
'This select all the records in the Categories table
oRs.Open "SELECT * FROM CATEGORIES", oCn
'This is used to hold all the records from the Categories table
Open "c:\categories.txt" For Output As #1 ' Open file for input.
'This actually writes the records to the categories text file.
Do Until oRs.EOF
Write #1, oRs("CategoryID").Value, oRs("CategoryName").Value '
Loop
oRs.Close
oCn.Close
Set oRs = Nothing
Set oCn =
Nothing
End Sub
This basically does the same thing
as our first example. It opens up the database and then exports the records in
to a text file called categories.txt.
Exporting Data IV
Private Sub ExpAmtPaid()
Dim db As Database
Dim rs As Recordset
Dim strFile As String
Dim intFile As Integer
Dim strFormat As String
strFormat = "mm/dd/yy"
strFile =
"C:\Windows\Temp\IGBackup\amtpd.csv"
intFile =
FreeFile
Open strFile For Output As intFile
'The path to the database is held in the txtBackup text box. This
'database requires a password.
Set db = OpenDatabase(txtBackupDB, False, False, ";pwd=mypwd")
Set rs = db.OpenRecordset("SELECT * FROM AmountPaid")
With rs
Do While Not .EOF
Print #intFile, !custInv; ","; !CustID; ","; !amtPaid; ","; Format$(!PayDate, strFormat); ","; !Paid
.MoveNext
Loop
.Close
End With
Set rs = Nothing
Set db = Nothing
Close intFile
End Sub
The above code exports the records in to the amtpd.csv file. You will notice
how to deal with dates when exporting. Since you are using a text file you
need to change the date in to a string in order to export the date.
Importing Data I
This week we will learn how to import records from the csv and txt files in to the database. If everything went well while you were exporting your files then you should have any problems importing the records.Importing Data II
This code uses ADO to import records in to a database.Importing Data III
He is another version of a import code.Importing Data IV
This code example uses the Input statement to import records in to an Access database.Importing Data V
This will complete the importing and exporting of data to and from a Database.
The code below uses the Open statement to import records from a csv file to
the database.
Private Sub ImportAmtPaid()
On Error Resume Next
Dim db As Database
Dim rs As Recordset
Dim CSVname As String
Dim fileName As Integer
Dim cName As Long
Dim cID As String
Dim cPaid As Currency
Dim pdDate As String
Dim pdYN
'The txtNewDB holds the path to the database
Set db = OpenDatabase(txtNewDB, False, False, ";pwd=pwd")
Set rs = db.OpenRecordset("TableName", dbOpenDynaset)
fileName =
FreeFile
CSVname = "C:\Windows\Temp\test.csv"
Open CSVname For Input As #fileName
Do Until EOF(fileName)
Input #fileName, cName
Input #fileName, cID
Input #fileName, cPaid
Input #fileName, pdDate
Input #fileName, pdYN
'Now add records to the database
With rs
.AddNew
!custInv = cName
!CustID = cID
!amtPaid = cPaid
!PayDate = CDate(pdDate)
!Paid =
pdYN
.Update
End With
Loop
Close #fileName
rs.Close
db.Close
End Sub
There are two things that you should note. One remember that when we exported
the date out of the old database we do so as a string. Now that we are importing
the date record it must then be converted back to a date format, that is why
the CDate is used.
The second thing is when importing a Boolean field it will only work if is its
not declared. Meaning the variable must be a variant, if you type the following
you will get a error when trying to import a Yes/No field.
Dim pdYN As Booleen
S/B
Dim pdYN
Altering a Database
While using the importing and exporting option to transfer data from one
database to another can resolve the problem of changing a database. In some
cases it may not be very efficient. If all you have are a couple of tables to
export and each table have a couple of fields then physically exporting and
importing records should not be a problem. However if you have a lot of tables
in your database that need to me exported due to a change in the database then
the best alternative would be to alter the table in lieu exporting all the
records out of the database.
This portion of our tutorial on Working With
Databases, well will explore the Alter statement for updating or changing a
database.
Alter Database - Adds or removes files and filegroups from a
database. Can also be used to modify the attributes of files and filegroups,
such as changing the name or size of a file. ALTER DATABASE provides the ability
to change the database name, filegroup names, and the logical names of data
files and log files.
Remember I'm using Access 97 for these examples,
the syntax my slightly very depending on which database you are using. Check
your database manual for the proper syntax for your database.
Altering Using Add and Drop
The Alter statement has these parts:
Table - The name of the table to be altered.
field - The name of the field to be added to or deleted from table.
type - The data type of field.
size - The field size in characters (Text and Binary fields only).
index - The index for field.
multifieldindex - The definition of a multiple-field index to be added to table.
indexname - The name of the multiple-field index to be removed.
ADD
The Add part of the Alter statement will allow you to add a column to a
table. This can be used when a feature you added to your application
requires you to have a new field in the database table. You can use
ADD COLUMN to add a single field to a table by specifying the field name,
data type and, optionally, a size for the Text and Binary fields:
The Add portion of the Alter statement looks like this.
ALTER TABLE Customer ADD COLUMN PhoneNum Text(15);
The above code will add a column to the Customer table
named PhoneNum that has the data type of Text and size of 15 characters.
You can add the reserved words NOT NULL to require valid data to be added
to that field:
ALTER TABLE Sales ADD COLUMN UnitPrice CURRENCY NOT NULL;
Foreign Key
The Foreign Key portion of the Alter statement allows you to add a
Foreign Key to a field. The Foreign Key statement looks like the following.
Alter Table Customer Foreign Key (CustID)
The above code will add a Foreign Key to the CustID field of the Customer
table.
Drop
The Drop portion of the Alter statement allows you to remove a column
for a table. You can also drop a PrimaryKey using the Drop statement.
The Drop statement looks like the following.
"Alter Table Customer Drop Column MName"
"Alter Table Customer Drop constraint PrimaryKey"
The above code will remove the
MName column in the Customer table. The second statement will remove the
PrimaryKey on the Customer table.
Adding Columns (Fields) using ADO, DAO
Our last demo showed how to add a field to an existing table in your database using the Alter statement. This will show you have to add a new fields using DAO CreateField and ADO Append.Putting it all together
Over the last couple of weeks we I have provided code sample that allowed you to export data from a database and import data to a database. I have also provided code samples that allowed you to alter an existing database. This portion of the tutorial will put it all together and provide you with a real example of importing and exporting and altering a database.
DBtools Export
The code below was used to export database out of an existing database. I used coma delimited method to export the records in to a csv file. Before you can save the cust.csv file you have to create a temp directory to hold the file. Once the import has taken place you would then delete the cust.csv file and delete the temp directory.
DBTools Import
The code below imports the records stored in the cust.csv file in to the new database.Example Alter
This examples uses the Alter statement to change the size of a field
in the Barcode table. Because I was using Access 97 I had to create a
temporary table, move the records to the temp table. Create a new table
that changed the data type of one of the fields, then copied the records
from the temporary table to the new one. I have commented the steps I took
on the code it self.
Option Explicit
Private Sub Command1_Click()
Dim db As Database
Dim sql As String
Dim sql2 As String
Dim sql3 As String
Dim sql4 As String
Dim sql5 As String
Dim sql6 As String
Dim sql7 As String
Dim sql8 As String
Dim sql9 As String
'Text1 holds the path to the database
Set db = OpenDatabase(Text1, False, False, ";pwd=pwd")
'Create a temporary table to hold the records
sql = "ALTER TABLE Barcode ADD COLUMN Temp Text(15)"
'Copy the records from the UPCNo field to the temp field
sql2 =
"Update Barcode Set Temp = [UPCNo]"
'Now remove the primary key so we can drop the UPCNo field
sql3 = "Drop Index PrimaryKey On Barcode"
'This table has two primary keys so drop the second one
sql4 = "Drop Index PartNo on Barcode"
'Now drop the old UPCNo field
sql5 = "Alter Table Barcode Drop Column UPCNo"
'Now create a new field with the updated text size
sql6 = "Alter Table Barcode Add Column UPCNo Text (15)"
'Now copy the records in the New UPCNo field
sql7 = "Update Barcode Set UPCNo = [Temp]"
'Now drop the Temp field
sql8 = "Alter Table Barcode Drop Column Temp"
'Now create a Primary Key and Index for UPCNo with no duplicates
sql9 = "CREATE UNIQUE INDEX PrimaryKey On Barcode (UPCNo)WITH PRIMARY"
db.Execute sql
db.Execute sql2
db.Execute sql3
db.Execute sql4
db.Execute sql5
db.Execute sql6
db.Execute sql7
db.Execute sql8
db.Execute sql9
db.Close
MsgBox "Update done!"
End Sub
If I was using Access 2000 then the above process would have been done with one
sql statement.
sql = "Alter Barcode Alter Column UPCNo Text(15)"
That would have been nice but Access 97 does not have the Alter Column method just
Add and Drop Column.
In Conclusion
Whether you are
creating, updating or changing a database this can easily be done using VB.
©Copyright 2002 Marietta Crockett
Disclaimer