0% found this document useful (0 votes)
51 views

RELATIVE PATH To The Database File

The document provides instructions on how to connect a Microsoft Access database to a Visual Basic application using ActiveX Data Objects (ADO) and structured query language (SQL). It explains how to configure the application files, design the database table, add records to the table using ADO and SQL commands, and ensure user input is properly formatted when adding records. Code examples are provided to generate new student IDs, call a function to capitalize names, and insert records into the database table using an ADO connection object.

Uploaded by

James Hernandez
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

RELATIVE PATH To The Database File

The document provides instructions on how to connect a Microsoft Access database to a Visual Basic application using ActiveX Data Objects (ADO) and structured query language (SQL). It explains how to configure the application files, design the database table, add records to the table using ADO and SQL commands, and ensure user input is properly formatted when adding records. Code examples are provided to generate new student IDs, call a function to capitalize names, and insert records into the database table using an ADO connection object.

Uploaded by

James Hernandez
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

Database Connectivity This tutorial shall show you how to connect to a Microsoft Access Database using Microsofts ActiveX

Data Object. This is a DSN-less connection that will only make use of a connection object to execute SQL Statements to the database. This means that you need to learn SQL to be able to issue the proper commands.

Before we program however, there are a few things about the configuration of the system files that needs to
be explained for all of these codes to work. Remember that this will NOT work without the Reference to Microsoft ActiveX Data Objects library (this particular project used 2.5) 1. The application path and File locations For the database connectivity to work, Visual Basic needs to know where the Database file is. So the connection string of the connection object usually has the path to the database file. The problem lies in the fact that if we decide to transfer this file to another location, the path wont work anymore hence, the connection fails. Heres the solution: put the Database file in the same folder as the Application/Project File and use a RELATIVE PATH to the database file. In our Example, heres how the system files look like: The whole system in located in a folder named Sample. Sample folders contents prjMyStudentMaintenance.vbp prjMyStudentMaintenance.vbw MSSCCPRJ.SCC frmAdd.frx frmDelete.frx frmEdit.frx Db dbStudents.mdb MS-Access Database File Visual Basic Project File Visual basic Workspace File Visual Basic Source Code File Visual Basic Form File Visual Basic Form File Visual Basic Form File Directory \ Folder

This way, if we decide to move the project to another location, we simply move the whole Sample folder and not worry about anything about the code. 2. The Database Structure The Database is dbStudents.mdb, it also has only one table inside named tblStudents which looks like this: The Design of tblStudents:

The Datasheet View of the table looks like this:

Note that the fldStudentName has this format: LASTNAME , FIRST NAME ,MIDDLE NAME 3. SQL Briefing SQL caters a lot of different data types and basically, we are dealing with three different data types here: Text\String, Number\Integer and Date\Time. As a reminder, heres how the values passed to the database through SQL should look like. Data Type Passing Value Text My Text Number Date\Time 130

#10/11/2005#

Adding Records to the Database Heres the full tutorial of how I add records to a database. Ive put some code that I will explain as we go through the process. Lets look at the form (looks innocent doesnt it? Freaky little creep a monster form it is I tell you!). Ive put names only to significant controls and left the others to their defaults.

txtStudID: this textbox is locked txtStudFN

txtStudMN txtStudLN

cmdAdd

cmdGenerateID
The form has the following flow. 1. The user creates an ID by clicking on the Generate ID Button. 2. The user inputs his or her First Name, Middle Name and Last Names 3. The user clicks the Add Button With that all set, lets pry into the code: First, lets take a look at how the program generates a new ID Number. This has a lot to do with how the ID Number looks like. The Typical ID Looks like this: 20050001 (where 2005 probably is the date and the numbers succeeding it refer to the order in which the user obtained the number) Heres the code:
Private Sub cmdGenerateID_Click() Connect to the Database and have a Recordset Object Dim Connec As New ADODB.Connection, Rs As New ADODB.Recordset We use the App.path to access the projects path and add in the db folder and the filename of our database Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" Select all student records from the table with fldStudentIDs that start with the Current Year and put them in the recordset. I got them in descending order This is how the SQL Statement should look like: ----Select * from tblStudents where fldStudentID like 2005% order by fldStudentID desc--Set Rs = Connec.Execute("Select * from tblStudents where fldStudentID like '" & Format(Date, "YYYY") & "%' order by fldStudentID desc") If we cant find a student that has such a student number, then this current student might be the first one to enroll this year. We will give him\her the first student number: 20050001 If Rs.BOF = True Then Me.txtStudID.Text = Format(Date, "YYYY") & "0001": Exit Sub If we do find a student with a similar ID number, then we get the last ID number and add 1 to that, we format the sum into four digits and that becomes our student number Me.txtStudID.Text = Format(Int(Rs("fldStudentID")) + 1, "####") having done what we came for, we close our connections and end the program Rs.Close Connec.Close End Sub

Making sure that the user inputs the correct format

The user may not know how to use systems like this, or the user maybe a naughty little git that we may have to make sure that he\she inputs the correct format of data in the textboxes.

For such instances, I choose to correct the wrongs in the users input. I make sure that for names, the program observes proper capitalization of names to make the names more presentable in the database. To do this, I create a function that properly capitalizes all things thats put into it.

This function returns a String Value named Proper This function requires a String Value named Str Function Proper(Str As String) As String the function gets the first leftmost character in Str ---------------------------Left(Str,1) next the function gets the capital letter of that character --------------------UCase(Left(Str,1)) next the function gets the Length of Str ----------------------------------------Len(Str) the function uses this length to get the middle of the string from the second character to the last ---------------------------------------------------------------------------------------Mid(Str,2,Len(Str)) if for example the string is gOshEn the length would be 6 the middle of the string from the second character to the sixth would be OshEn the function then gets the lowercase of this string ---------------------------LCase(Mid(Str,2,Len(Str))) the function concatenates the capitalized First letter to the rest of the string the function trims the finished product, deleting the extra spaces before and after the letters --------------------------------------------------------------------------------------Trim( ) the function returns the value and puts it into Proper--- the variable and there you have it its a one liner code that does a lot of things Proper = Trim(UCase(Left(Str, 1)) & LCase(Mid(Str, 2, Len(Str)))) End Function

Next, what I did is call the code in all of my Name textboxes.


Private Sub txtStudFN_KeyPress(KeyAscii As Integer) When the user presses the ENTER KEY with a KeyAscii of 13, its time to put things into Proper If KeyAscii = 13 Then the contents of the textbox is confiscated and replaced by it Proper counterpart txtStudFN.Text = Proper(txtStudFN.Text) If the user already pressed the ENTER KEY, that means that he must be finished with the firstname and may probably is ready to go on to the middle name. Me.txtStudMN.SetFocus End If End Sub

*Just do this for all text boxes and youve made sure that every name comes out right. *One thing left to do here: If the user inputs a compound name like Ma. Makiling or something, the current program doesnt support putting the second name into its proper format (Im thinking you could do that for your Finals hehehe!) A clue Do loop and look for spaces using instring function.

Adding a Record to a Database Table Using an SQL Command and an ADO Connection Object (Lipad po ang tawag don) Well, actually NOBODY does this. Only a handful of people could pull off adding records to a database table using only one ADO Object--- the connection object. Now you know the Legend of the flying SQL Statement.
Private Sub cmdAdd_Click() We check if there are textboxes that are left with no values we use the length of the string if the length is 0 then, the textbox is empty if the textbox is empty, we issue appropriate error messages and then quit If Len(Me.txtStudFN.Text) = 0 Then MsgBox "Please input your First Name.", , "Add Student": Exit Sub If Len(Me.txtStudID.Text) = 0 Then MsgBox "Please click the Generate ID Button to create your Student ID Number.", , "Add Student": Exit Sub If Len(Me.txtStudLN.Text) = 0 Then MsgBox "Please input your Last Name", , "Add Student": Exit Sub If Len(Me.txtStudMN.Text) = 0 Then MsgBox "Please input your Middle Name", , "Add Student": Exit Sub We connect to the database Dim Connec As New ADODB.Connection, Rs As New ADODB.Recordset Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" We use the Recordset to search the database for a student with a similar Student Name the code in the parentheses yields this SQL ----Select fldStudentID from tblStudents where fldStudentName = LastName FirstName MiddleName Set Rs = Connec.Execute("Select fldStudentID from tblStudents where fldStudentName = '" & Me.txtStudLN.Text & "," & Me.txtStudFN.Text & "," & Me.txtStudMN.Text & "'") If we do find a student with exactly the same name, then, this must be a duplicate entry we tell the user of the mistake, close the recordset and quit If Rs.BOF = False Then MsgBox "Duplicate Entry", , "Add Student": Rs.Close: Exit Sub If we dont need the recordset, lets close it to reduce dependencies Rs.Close Now we perform the actual data Add We use the execute method to throw the SQL statement to the database --- IN your FACE! Punk! The SQL formed between the parentheses looks like this Insert into tblStudents (fldStudentID,fldStudentName,fldEnrollDate) values ( 20050001, = LastName FirstName MiddleName , #10/11/2005# ) The --, , adExecuteNoRecords ---- let ADO know that it is not going to retrieve records from the database Connec.Execute "Insert Into tblStudents (fldStudentID,fldStudentName,fldEnrollDate) values (" & Int(Me.txtStudID.Text) & ",'" & Me.txtStudLN.Text & " " & Me.txtStudFN.Text & "," & Me.txtStudMN.Text & "',#" & Date & "#)", , adExecuteNoRecords Having done that, we close the connection Connec.Close And tell the user we had good hits MsgBox "Add successful" End Sub

This is basically your non-basic ADO Connection

Editing Records in the Database This tutorial is about editing a record from the database. Remember the Steps to Editing the Record 1. Let the user pick the record to be edited. 2. Show the record he picked on the screen. 3. Dont let him edit the record unless he presses the Edit Button, this is a standard operating procedure. If a user who chooses a wrong record mistakably presses keyboard keys, then, the data on the screen will be altered and it will be a total mess. To avoid this, let the user say please so to speak. 4. Let the user edit the record on his own; but correct the mistakes he commits. 5. If all goes well at this point, let the user save the changes by clicking the Save button. Heres the form:

txtStudID: this textbox is locked cboFullnames txtStudFN: this textbox is locked

txtStudMN: this textbox is locked txtStudLN: this textbox is locked

cmdEdit

cmdSave: this button is disabled


Firstly, we need to give the user some choices after all, the user has to pick a record up right? So I thought of putting the combo box there to provide the user some way of picking which student record to edit. So how do we get the records from a database table into a combo box?... and When? A good idea is to do whatever we want to do during the Form Load event. The Form Load event happens before we see the form on the screen (its a backstage preparation pal!) Populating a lonely Combo box with records from a database table during Form Load
Private Sub Form_Load() Get the connection set up Dim Connec As New ADODB.Connection, Rs As New ADODB.Recordset Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" Collect the data with the use of your Recordset (in this case we get all the StudentNames) Set Rs = Connec.Execute("Select fldStudentName from tblStudents") This is an error trapper in case the recordset comes back empty, we simply close the record set and quit If Rs.BOF = True Then Rs.Close: Exit Sub make sure to start from the beginning of the list Rs.MoveFirst Go over each record in the recordset by saying do this till the End Of File Do While Not Rs.EOF Add the content of the recordset to the combo box Me.cboFullNames.AddItem Rs("fldStudentName") Skip to the next record Rs.MoveNext Loop Dont forget to close the recordset and the connection object afterwards Rs.Close

Connec.Close End Sub

Displaying the Record on the Screen When the user has made up his mind and picked a record from our list, we must display the said record onto the screen. We use the Combo Boxs onClick event to do this.
Private Sub cboFullNames_Click() 1) Fetch the students ID number from the database Crank up the connection Dim Connec As New ADODB.Connection, Rs As New ADODB.Recordset Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" here we collect the ID number from the database table the SQL looks like this ----Select fldStudentID from tblStudents where fldStudentName = LastName FirstName MiddleName Set Rs = Connec.Execute("Select fldStudentID from tblStudents where fldStudentName = '" & Me.cboFullNames.Text & "'") for once we are certain that we will get arecord from the database why because the information we used to get the data also came from the database! all we have to do now is to put the ID on the textbox Me.txtStudID.Text = Rs("fldStudentID") we dont need the recordset any more so close this together with the connection object Rs.Close Connec.Close Now we have to show the First Name, Middle Name and the Last Names separately on different tectbox even though it came from just one record -im declaring a variable Ill be needing later this is improper but hey! It works! Dim Spare As String First off, we get the last name, since this is the easiest to get. Since the name is separated by commas, we locate the first comma ---- Instr(me.cboFullNames.Text) then we get the leftmost substring of the lot until the first comma minus 1 minus 1 because we dont want to include the comma itself. We only want the letters to the left of it we Trim the whole thing to get the extra spaces out Me.txtStudLN.Text = Left(Me.cboFullNames.Text, InStr(Me.cboFullNames.Text, ",") - 1) I now use my Spare string first, I get the middle of the whole string from the right of the first comma to the last one we determine the character number of the last letter by asking how long the string is. -----------Len(Me.cboFullNames.Text) I also So now the Spare contains this: FirstName MiddleName Spare = Trim(Mid(Me.cboFullNames.Text, InStr(Me.cboFullNames.Text, ",") + 1, Len(Me.cboFullNames.Text))) I use the same technique I did with the last name to fetch the First Name from the Spare trim it and youre done Me.txtStudFN.Text = Trim(Mid(Spare, 1, InStr(Spare, ",") - 1)) I look for the comma in the spare and sice there is only one comma, I get the characters that come from the right of that to the end of the string and poof! I now have the Middle name! dont forget the trim guys Me.txtStudMN.Text = Trim(Mid(Spare, InStr(Spare, ",") + 1, Len(Spare))) End Sub

Applying Locks Ive said earlier that its improper to let the user just edit the record after displaying it. Now, I teach you how to lock and unlock textboxes with the use of just one button (not Two)

In a sense, its not actually the Edit Button that edits the records from the database its the Save Button. The Edit Button is just there for unlocking the textboxessoyeah the user doesnt know about that but who cares? Heres how to turn that Edit Button into a lock and Unlock button for the textboxes.
Private Sub cmdEdit_Click() We make the button perform dual tasks by applying modes to it If the Button is in Edit mode, then we unlock the textboxes And when it is in Back mode, we lock then up If cmdEdit.Caption = "Edit" Then The button is in Edit mode so we unlock the textboxes excluding the Student ID this is because Student IDs are primary keys and primary keys arent supposed to be edited. Me.txtStudFN.Locked = False Me.txtStudLN.Locked = False Me.txtStudMN.Locked = False If the user edits the record, then we should allow him to save the changes cmdSave.Enabled = True Change the mode of the Button to Back Mode cmdEdit.Caption = "Back" Else The button is in Back Mode so lets go back to the original Setup. Lock the textboxes as they were from the start Me.txtStudFN.Locked = True Me.txtStudLN.Locked = True Me.txtStudMN.Locked = True Disable the Save button cmdSave.Enabled = False And change to Edit Mode cmdEdit.Caption = "Edit" End If End Sub

This is only a few of the many wonderful things we can do with IF Then ELSE Statement youll get to know all of those other wonderful things when you are out there trying to thinks of ways to make your future program work. With that set, I would like to point out that the editing process also needs the same treatment as the Adding of Records. So I also impose my Proper Function and the KeyPress methods on the text boxes. Just see the Making sure that the user inputs the correct format tutorial.

Saving the Changes --- the Actual Editing

By virtue, it is not the Edit Button that edits the record it is the Save Button. So now, we would perform the actual editing of records in the Save button. The code is as follows:
Private Sub cmdSave_Click() As usual, we check the textboxes if they are left with nothing changed the title of the error messages to Edit Student If Len(Me.txtStudFN.Text) = 0 Then MsgBox "Please input Student": Exit Sub If Len(Me.txtStudLN.Text) = 0 Then MsgBox "Please input Exit Sub If Len(Me.txtStudMN.Text) = 0 Then MsgBox "Please input Student": Exit Sub the same code except that Ive your First Name.", , "Edit your Last Name", , "Edit Student": your Middle Name", , "Edit

Connect to the database Dim Connec As New ADODB.Connection, Rs As New ADODB.Recordset Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" Here, we check for duplicate entries Im checking for student with the same student name but has another student number the SQL looks like this Select fldStudentID from tblStudents where Not(fldStudentID = Idnumber ) and fldStudentName = LastName FirstName MiddleName Set Rs = Connec.Execute("Select fldStudentID from tblStudents where Not(fldStudentID= " & Int(txtStudID.Text) & ") and fldStudentName = '" & Me.txtStudLN.Text & "," & Me.txtStudFN.Text & "," & Me.txtStudMN.Text & "'") If the recordset is not empty, we have a problem, the student tried to change his name into the name of his classmate --- we certainly cannot allow that We tell him off and quit If Rs.BOF = False Then MsgBox "Duplicate Entry", , "Edit Student": Rs.Close: Exit Sub NEVER forget to close the record set if you dont need it anymore Rs.Close Heres the fun part, If all goes well with the user, we just edit the record by throwing an Update SQL Statement to the database The same LIPAD I told you about in the Add Student the SQL Statement looks like this Update tblStudents Set fldStudentName = LastName FirstName MiddleName where fldStudentID = Idnumber Connec.Execute "Update tblStudents Set fldStudentName = '" & Me.txtStudLN.Text & "," & Me.txtStudFN.Text & "," & Me.txtStudMN.Text & "' where fldStudentID = " & Int(Me.txtStudID.Text) Close the connection Connec.Close Tell the user it is a success MsgBox "Edit successful" End Sub

Deleting Records from a Database And here we are at the last tutorial; we are now going to delete a record from a database table. Remember that deleting is a delicate process because once we delete a record; we simply cannot put it back. With this in mind, I have devised the following form procedure or flow: 1. The user searches for the record to be deleted. 2. The program displays the details on the screen and the Delete button is enabled. 3. The program asks the user to confirm the delete. 4. The program deletes the record.

txtStudID: this textbox is locked cboFullnames txtStudFN: this textbox is locked

txtStudMN: this textbox is locked txtStudLN: this textbox is locked

cmdDelete: this button is disabled


Now lets see how I did this, first, I devise a plan of making the user feel comfortable when picking up the record to delete. This is much like the record picker in the Edit Form. For this part, just see the Populating a lonely combo box with records from a database and the Displaying the record on the Screen tutorials. Enough of that lets jump to the deleting the record already. When the user has already picked a record and decides to delete the record, we have the following code.
Private Sub cmdDelete_Click() This message box does a lot because it gets values --- vbYes or vbNo This code displays a message box that asks the user if he really wants to delete the record. The message box offers him two choices, Yes and No If he picks Yes, the message box has a value of vbYes and vbNo if otherwise Now we ask if the message box what value it has and if has a value of vbYes, if it is, then we proceed If MsgBox("Do you really want to delete this record?", vbYesNo, "Delete Student") = vbYes Then We proceed by connecting to the database Dim Connec As New ADODB.Connection Connec.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & App.Path & "\db\dbStudents.mdb" Now we throw an SQL statement that deletes the record from the table heres the sample SQL Delete from tblStudents where fldStudentID = IDNumber Connec.Execute "Delete from tblStudents where fldStudentID = " & Int(Me.txtStudID.Text) We close the connection and tell the user that the delete went fine Connec.Close MsgBox "Delete Successful.", , "Delete Student" End If End Sub

Thats all there is to it. Remember that Security is always an issue in programming systems so whatever you do, PROTECT YOUR DATA! So guys, that wraps up the Database Connectivity Tutorial see you on the next flight!

You might also like