View
78
Download
0
Category
Preview:
DESCRIPTION
Database vs. DBMS. Database A collection of organized, related tables (data stored in rows and columns) Database Management System Also known as DBMS Software used to create and maintain a database. Entity-Relationship Diagram. Also known as ERD - PowerPoint PPT Presentation
Citation preview
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Database vs. DBMS Database
A collection of organized, related tables (data stored in rows and columns)
Database Management System Also known as DBMS Software used to create and maintain a database
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Entity-Relationship Diagram Also known as ERD
Graphical representation showing the relationships of entities in a database
Entities things of interest to business (products, employees,
suppliers, customers, purchases, sales,…)
Relationships real-world associations between entities
– products purchased by customers
– employees who designed a particular part
– suppliers who provided a particular raw material
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
ERD CardinalityRelated to one
Related to one or zero (optional)
Related to zero or more
Related to one or more
Student Course Teacher
Each course belongs to a specific teacher (manager)A teacher may teach one or more coursesA student can sign up for one or more coursesA course may have no students (not offered)
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Normalized Databases Normalization
A process of organizing database tables to increase stability through reduced (controlled) data redundancy.
Higher normal forms further restrict how attributes are grouped within records
3NF (Third Normal Form) is the generally accepted, minimum standard for designing a database
Every nonkey field is directly related to only to the entire key field and nothing else
– {Emp # (key), Emp Name, Dept Code, Dept Name} is not in 3NF since Dept Name can be derived entirely from dept code (both non-key fields)
– {Prod # (key), Prod Name, Qty, Cost, ValueinInventory} is not in 3NF since ValueInInventory is a calculated value (from Qty & Cost)
– {RawMat # (key), Prod #, AmtReqrd} is not in 3NF since AmtReqrd is derived from both RawMat# and Prod #
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Database TerminologyNorthwind DB tables
Records 3, 6 8 are condiments
Second record or row of Categories table describes condiments
Key fieldsRelationship based on shared data in two tables
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Databases Accessible by VB VB Native format
Microsoft Jet database engine Microsoft Access
Jet engine can also access Excel, dBASE, FoxPro, Lotus, Paradox, text files
VB Professional with Open DataBase Connectivity (ODBC) drivers Can also access SQL Server, Oracle, and DB2
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Data Control
data control
Provides access to data stored in databases using any one of three types of Recordset objects: table snapshot synaset
Enables data navigation viewed through bound controls.
Without a Data control, data-bound controls on a form can't automatically access data.
Validate event occurs just before new record becomes current.
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Data Control Properties Caption
Text that appears inside the control on the form Connect
Identifies DBMS source of database (Access) DatabaseName
Assigns the database filename with path (use dialog) ReadOnly
Defaults to False & must be set to true if user is not allowed to change contents
RecordSource Assigns the table or query (view) of the database to be used by the
VB program BOF and EOF
Flags set to true when current record pointer positioned before first record or after last record
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Data-Bound Controls Same controls we’ve used thus far with additional
properties set Labels (user cannot change), Textboxes (user can change),
Checkboxes (T/F or Y/N), etc.
DataSource point to database (specify name of data control)
DataField field name in database table that relates to this
It is possible to navigate data in a database simply by designing a form with the data control and binding data-aware controls to the data control -- no coding is needed!
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Programming the Data Control Recordset Object
Defined by setting RecordSource property of data control
Accessing Recordset properties in code datName.Recordset.Property Since this represents a value, it can only be part of
a statement (e.g., assign it to variable or assign something to it)
Applying methods to Recordset object datName.Recordset.Method Since this represents a process, it is written like a
statement
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Recordset Properties Checking the database pointer
datName.Recordset. BOF Flag that is true when record pointer is before first database
record (select previous on first record) datName.Recordset. EOF
Flag that is true when record pointer is after last database record (select next on last record)
Counting the number of DB records datName.Recordset.RecordCount
Setting or tracking the current DB record datName.Recordset.BookMark
Determining if desired record was found datName.Recordset.NoMatch
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Recordset Move & Refresh Methods Navigating DB via Code
Move to next database record datName.Recordset.MoveNext
Move to last database record datName.Recordset.MoveLast
Move to previous database record datName.Recordset.MovePrevious
Move to first database record datName.Recordset.MoveFirst
Refresh method Explicitly opens the database
datName.Refresh
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Adding a First buttonPrivate Sub cmdFirst_Click()
datEx.Recordset.MoveFirst
lblRecNum.Caption = 1
End Sub
cmdFirst_Click
RecNum = 1
End
Move to db record 1
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Adding a Last buttonPrivate Sub cmdLast_Click()
datEx.Recordset.MoveLast
lblRecNum.Caption = _
datEx.Recordset.RecordCount
End Sub
cmdLast_Click
RecNum = RecordCount
End
Move to last db record
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Adding a Next buttonPrivate Sub cmdNext_Click()
datEx.Recordset.MoveNext
If datEx.Recordset.EOF Then
Call MsgBox(“msg”,…)
Call cmdFirst_Click
Else
lblRecNum.Caption = _
CInt(lblRecNum.Caption)+1
EndIf
End Sub
cmdNext_Click
cmdFirst_Click
End
Move to next db record
EOF?TrueFalse
RecNum=RecNum+1
Display already at end - go to start
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Adding a Previous buttonPrivate Sub cmdPrevious_Click()
datEx.Recordset.MovePrevious
If datEx.Recordset.BOF Then
Call MsgBox(“msg”,…)
Call cmdLast_Click
Else
lblRecNum.Caption = _
CInt(lblRecNum.Caption)-1
EndIf
End Sub
cmdPrevious_Click
cmdLast_Click
End
Move to previous db record
BOF?TrueFalse
RecNum=RecNum-1
Display already at start - go to end
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Recordset Find Methods Search for a specific type of record and then move to
it in the specified direction. Specifying search criteria
<DBFieldName> <relational operator> <expression>
Find methods define starting point & search direction Start at first record and search forwards
datName.Recordset.FindFirst (search criteria) Start at last record and search backwards
datName.Recordset.FindLast (search criteria) Start at current record and search forwards
datName.Recordset.FindNext (search criteria) Start at current record and search backwards
datName.Recordset.FindPrevious (search criteria)
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Searching Example1) Save the current record
CurRecord = datName.Recordset.BookMark
3) Assign search criteriaSearchStr = InputBox(“prompt”, “title”, “default”)
Target = “TableName.FieldName = `” & SearchStr & “`”
3) Use search criteriaCall datName.Recordset.FindFirst(Target)
If datName.RecordSet.NoMatch Then
Call MsgBox(“ERROR”)
Else
‘ whatever processing needs to be done with current record
End If
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Example: Find similar namePrivate Sub cmdFindName_Click()
Dim CurRecord As Variant
Dim SearchString As String
' Save location of current record
CurRecord = datEmployee.Recordset.Bookmark
SearchString = "EmpName Like '" & _
txtSearchName.Text & "*'"
Call datEmployee.Recordset.FindFirst(SearchString)
If datEmployee.Recordset.NoMatch Then
Call MsgBox("No such employee", _
vbOkOnly + vbInformation)
' Move pointer to previously saved location
datEmployee.Recordset.Bookmark = CurRecord
Else
' fill display controls with found record’s data
Call ShowDBData
End If
End Sub
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Methods to change DB content Delete current database record datName.Recordset.Delete
be sure to add step to go to a valid record AddNew database record datName.Recordset.AddNew
clears data bound controls so user can enter new data DB automatically updated by moving to another record or explicitly
saving record Edit database record datName.Recordset.Edit
moves current DB record to copy buffer to allow changes to occur Update database with addition datName.Recordset.Update
explicitly saves newly entered data Reset db to previous values
datName.Recordset.UpdateControls
resets data bound controls to previous values
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Example: Add a new recordPrivate Sub cmdAddRec_Click()
If cmdAddRec.Caption = "&Add" Then ' 1) Clear input controls
Call DisableNavigation
Call datEmployee.Recordset.MoveLast
txtID.Text = Format(datEmployee.Recordset!empid + 1)
Call datEmployee.Recordset.AddNew
txtEmpName.Text = ""
txtBirthdate.Text = ""
txtPayRate.Text = ""
' Change caption to Save and disable other buttons
cmdAddRec.Caption = "&Save"
Call txtEmpName.SetFocus
Else ' the caption must be &Save ' 2) Write user input to DB
Call WriteDBData
datEmployee.Recordset!empid = txtID.Text
Call datEmployee.Recordset.Update
' Change caption to Add and enable other buttons
cmdAddRec.Caption = "&Add"
Call EnableNavigation
End If
End Sub
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Example: Delete a recordPrivate Sub cmdDeleteRec_Click()
Dim CurRec As Variant
CurRec = datEmployee.Recordset.Bookmark ' The record to delete
datEmployee.ReadOnly = False
Call datEmployee.Refresh
Call datEmployee.Recordset.MoveLast
datEmployee.Recordset.Bookmark = CurRec
Call datEmployee.Recordset.Delete
datEmployee.ReadOnly = True
Call datEmployee.Refresh
' Move to the last record
Call cmdLast_Click
If datEmployee.Recordset.EOF Then ' Last record was deleted
Call cmdFirst_Click
If datEmployee.Recordset.BOF Then ' No records left
Call MsgBox("There are no records left-the database" & _
" is empty", vbOkOnly + vbInformation)
End If
End If
End Sub
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Example: Change a recordPrivate Sub cmdModifyRec_Click()
' The current record will be the one to be modified
If cmdModifyRec.Caption = "&Modify" Then ' 1) Allow edit of record
Call DisableNavigation
Call datEmployee.Recordset.Edit
' Change caption to Save and disable other buttons
Call txtEmpName.SetFocus
cmdModifyRec.Caption = "&Save"
cmdDeleteRec.Enabled = False
cmdAddRec.Enabled = False
Else ' the caption must be &Save ' 2) Copy updates to DB
Call WriteDBData
Call datEmployee.Recordset.Update
' Change caption to Modify and enable other buttons
cmdModifyRec.Caption = "&Modify"
cmdDeleteRec.Enabled = True
cmdAddRec.Enabled = True
Call EnableNavigation
End If
End Sub
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Preventing Errors
Examples: The primary key must
be non-blank All data entered must
be of correct type and length
The database table has valid records (not an empty table)
Pseudocode/Algorithm
If a required field is empty and both BOF and EOF are False Then
Show error msg
Reset error condition so program can run
Don’t save changes
Endif
Add code to the Validate Event of data control Add error handlers in all procedures that access DB
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Checking for Empty RecordsetsIf BOF and EOF Then
Display error message
End If By checking for both BOF & EOF, you are
checking for a recordset with no members
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Queries: Joining DB tables1) Define query to get all unique field names from both tables
Query = “Select * From TableName1, TableName2 Where ” & _
“ TableName1.FieldX = TableName2.FieldY”
Query = “Select TableName1.FieldA, TableName1.FieldB, “ & _
“TableName2.FieldZ Where TableName1.FieldX = “ & _
“TableName2.FieldY”
2) Assign Query to RecordSource property & Open the DBdatName.RecordSource = Query
Call datName.Refresh
3) Start at the first recordCall datName.Recordset.MoveFirst
4) Assign value in current DB field to control on formlblName.Caption = datName.Recordset(“FieldName”)
lblName.Caption = datName.Recordset!FieldName
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Filling list with DB field choices1) Get filename from user (common dialog)
2) Assign user’s file selection to DatabaseName property of data control
3) Define query to get all unique field namesQuery = “Select Distinct FieldName From TableName”
datName.RecordSource = Query
4) Use Refresh method to open the databaseCall datName.Refresh
5) Clear the list & add any general choices (“Show All”)
6) For each item in the database, add the item to the list and go to next item until doneCall cboName.AddItem(datName.Recordset(”FieldName"))
Call cboName.AddItem(datName.Recordset!FieldName)
© 1999, by Que Education and Training, Chapter 10, pages 511-545 of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach
Returning select DB records1) Define query using user’s selection
a) General “Show All” choice: Query = “Select * From TableName”
b) Otherwise: Query = “Select * From TableName Where “ & _
“FieldName = `“ & cboName.Text & “`”
2) Assign Query to data controldatName.RecordSource = Query
3) Use Refresh method to open the databaseCall datName.Refresh
4) If flexgrid is used on the form, it will automatically contain all fields of the desired records based on the search criteria
Recommended