Visual Basic Database Programming.

Slides:



Advertisements
Similar presentations
ADO DB in Access VBA © Walter Milner 2005 Slide: 1 ADO VBA Programming in Access.
Advertisements

MS-Access XP Lesson 1. Introduction to MS-Access Database Management System Software (DBMS) Store data in databases Database is a collection of table.
Customizing Reports. Custom Reports A report is a formatted hardcopy of the contents of one or more tables from a database. Although you can format and.
Start First step Create a new blank database Create a database using the option that will enable you to build your database using pre-set options. Save.
Create a new blank database First step SUBMITTry again.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Mark Dixon, SoCCE SOFT 131Page 1 16 – Persistent data storage: relational databases and ADO.
Mark Dixon Page 1 17 – Persistent data storage: relational databases and ADO.
Mark Dixon, SoCCE SOFT 131Page 1 24 – Web applications: Writing data to Databases using ASP.
Creating Custom Forms. 2 Design and create a custom form You can create a custom form by modifying an existing form or creating a new form. Either way,
ActiveX Data Object ISYS 562. ADO An ActiveX control ActiveX is build upon COM, a contract that defines a standard interface by which objects communicate.
Using Visual Basic 6.0 to Create Web-Based Database Applications
Using Objects and Properties
Mark Dixon Page 1 18 – Persistent data storage: relational databases and ADO.
Mark Dixon Page 1 20 – Web applications: Writing data to Databases using ASP.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Handling of data from multiple databases. Visual Basic Database Visual Basic application acts as a front-end to the database Visual Basic application.
Copyright © 2001 by Wiley. All rights reserved. Chapter 10: Advanced Database Operations Revising Vintage Videos Setting RecordSource at run time DBGrid.
McGraw-Hill/Irwin Programming in Visual Basic 6.0 © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Update Edition Chapter 11 Accessing Database.
Mark Dixon Page 1 23 – Web applications: Writing data to Databases using ASP.
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
Recordsets Chapter 7. Recordset Objects Similar to Tables and Queries: data But forms cannot be bound to them Fields cannot be bound to them But Access.
Lecture Note 10: Simple Database Techniques. Introduction –Database System –Access, SQL Server and others. –Microsoft Access - Interacting with this databases.
Visual Basic ADO Programming 56:150 Information System Design.
Database Systems Microsoft Access Practical #3 Queries Nos 215.
1 Database Design and Development: A Visual Approach © 2006 Prentice Hall Chapter 8 DATABASE DESIGN AND DEVELOPMENT: A VISUAL APPROACH Chapter 8 Creating.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
ActiveX Data Objects (ADO) is Microsoft’s latest database object model. The goal of ADO is to allow VB developers to use a standard set of objects to refer.
Tutorial 91 Databases A database is an organized collection of related information stored in a file on a disk A database allows companies to store information.
Mark Dixon Page 1 21 – Web applications: Writing data to Databases using ASP.
Databases,Tables and Forms Access Text by Grauer Chapters 1 & 2.
1 Database Systems Introduction to Microsoft Access Part 2.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
INSERT BOOK COVER 1Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Getting Started with VBA for Microsoft Office 2010 by.
Unbound Form Form not tied directly to any fields in the database Must use SQL to “bind” the fields 1.
Lab 8 Data Access Using Microsoft ActiveX Data Object (ADO)
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Database Connectivity What is ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a Microsoft Active-X component.
IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
Source = Table rsObject.Open tablename, Connection Object, CursorType, LockType, adCmdTable Source = Stored Procedure rsObject.Open stored procedure name,
Using a Database Access97 Please use speaker notes for additional information!
Labtest.ASP Notes. INSERT STATUS INSERT STATUS
XP New Perspectives on Microsoft Office Access 2003, Second Edition- Tutorial 6 1 Microsoft Office Access 2003 Tutorial 6 – Creating Custom Forms.
Copyright © 2009 Pearson Education, Inc. Publishing as Prentice Hall. 1 Skills for Success with Microsoft ® Office 2007 PowerPoint Lecture to Accompany.
 2 Data Object Library approaches ◦ DAO (Data Access Objects)  Original access strategy (up to VB6)  Closely linked to MS Access ◦ ADO (ActiveX Data.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 11 Creating Web Applications and Writing Data to a Database.
ASP.NET Programming with C# and SQL Server First Edition
Excel Tutorial 8 Developing an Excel Application
Using Macros, Switchboards, PivotTables, and PivotCharts
ADO VBA Programming in Access
Find, filter etc with connection to Access code internally
18 – Databases: Structured Query Language
Microsoft Office Access 2010 Lab 2
Database vs. DBMS Database Database Management System
INT213 Updating the Database.
Developing Forms and Subforms.
Microsoft Office Access 2003
ربط الفيجوال بيسك VB مع قواعد البيانات
Chapter 7 Advanced Form Techniques
Microsoft Office Access 2003
Microsoft Office Access 2003
Department Array in Visual Basic
Introduction to Access
Working With Databases
17 – Persistent data storage: relational databases and ADO
Excel Import data from Access to Excel (ADO) using VBA
Chapter 7 Database Basics
Presentation transcript:

Visual Basic Database Programming

Topic & Structure of the lesson Introduction Database Concepts Active X ADODB Add Records Update Delete Records

Learning Outcomes At the end of this lecture, you should be able to : Create a database table Use Active X Data Objects (ADODB) Write Structured Query Language (SQL) Add Records Update Records

Key Words used in this lecture If you have mastered this topic, you should be able to use the following terms correctly in your assignments and exams: ADODB Add New Update Open Close EOF

Creating a Database Table Start Microsoft Access Create a table Enter the field names Ensure that you have a primary key field Save the table as tblstudent

Active X Data Objects (ADODB) Newest Database Connectivity method in VB6.0. Supports Hierarchical Flexi Grid Control. Easier to program and debug. Allows Connection String method to connect to a database.

Steps to Connect To A Database Select Project References Select Microsoft ActiveX Data Objects 2.1 Library Write the connection string to connect to a database

Database Connection Dim cn as adodb.connection Private Sub Form_Load() Dim connstring As String Set cn = New ADODB.Connection connstring = “Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\newadodb\devin.mdb" cn.Open connstring End Sub

Group Exercise Write a procedure to connect to a database called library.mdb

Adding A New Record Execute the recordset’s AddNew method. This adds a new, blank record to the end of the recordset. Assign values to the new record. Write the record to the database using the recordset’s Update method.

Adding A New Record Private Sub cmdadd_Click() dim rs as adodb.recordset set rs = new adodb.recordset Dim strsql As String strsql = "select * from login where firstname = null" rs.Open strsql, cn, adOpenKeyset, adLockOptimistic rs.AddNew rs.Fields("id") = Val(Txtid.text) rs.Fields("firstname") = txtfirstname.text rs.Fields("lastname") = txtlastname.text rs.Fields("age") = Val(txtage.text) rs.Update rs.Close End Sub

Quick Review Question Write a procedure to accept Student-ID, student name, address, phone-number from text boxes. Write the record to a student-table.

Basic SQL Statements SELECT * from TableName WHERE criteria (*) indicates all fields from a Table Select * From Student Where name = ‘John’ Select StudentID, Name from tblstudent Select * from Student where name = ‘”& txtname.text & “’” Select * from tblstudent order by name – To Sort by Name

Quick Review Question Write a SQL statement to select all fields from tblpassenger. Write a SQL statement to select passengerID, name, address and phone from tblpassenger. Write a SQL statement to select all fields from tblpassenger where name = Smith Write a SQL statement to select all fields from tblpassenger where name is from a textbox input.

Updating a Record Used to update a record or group of records Search the specific records using an SQL statement. If the record is found then update the record using Update method. Use an EOF Statement to check if a record exist If the record is not found display an Error Message. Close the recordset once update is complete

Updating a Record Private Sub cmdupdate_Click() Dim rs as adodb.recordset ‘declare recordset Set rs = new adodb.recordset ‘set the recordset Dim strsql As String strsql = “select * from login where ID = “ & txtid.text & “” rs.Open strsql, cn, adOpenKeyset, adLockOptimistic If rs.eof then ‘Record Does Not Exist Msgbox “Record Not Found” Else rs.Fields("age") = Val(txtage.text) rs.Update End if rs.close End Sub

Quick Review Question Write a procedure to search for a Student ID and update the student’s address and phone number. If the studentID is not found display an error message using a Msgbox. Use tblstudent as the table name.

Deleting a Record To delete a record or group of records. Search for a record to be deleted. Use .EOF to check if record is found. Use .delete command to delete the record.

Deleting a Record Private Sub Command2_Click() Dim strsql As String Dim rs as adodb.recordset Set rs = new adodb.recordset strsql = “select * from login where firstname = ‘ ” & txtfirstname.text & “ ’ ” rs.Open strsql, cn, adOpenKeyset, adLockOptimistic If rs.EOF Then MsgBox "Record Not Found" Else rs.Delete End If rs.Close End Sub

Quick Review Question Write a program to request for a Student-ID and delete it from the student-table. If the Student-ID is not found display an error message using a MsgBox.

Question and Answer Session Q & A

Next Session Displaying and Searching Records

Displaying and Searching Records

Learning Outcomes At the end of this lecture you should be able to: Display records to a list box Select records from a lit box Search records using the like operator Display records to a combo box

Key Words List Box Do Until Like If you have mastered this topic, you should be able to use the following terms correctly in your assignments and exams: List Box Do Until Like

References Database Access with Visual Basic 6 Jeffrey P Mc Manus SAMS Publication Visual Basic 6 How to Program Deitel and Deitel Chapter 18

Display Records to a List Box Private Sub Command4_Click() Dim rs As ADODB.Recordset Set rs = New ADODB.Recordset Dim sql As String sql = "Select * from login" rs.Open sql, cn, adOpenKeyset, adLockOptimistic List1.Clear

Display Data to a List Box Do Until rs.EOF List1.AddItem rs.Fields("firstname") List1.ItemData(List1.NewIndex) = rs.Fields("ID") rs.MoveNext Loop End Sub

Group Exercise Write a procedure to display all students name from tblstudent to a listbox.

Search Using List Box Click Event Private Sub list1_click() Dim rs as adodb.recordset Dim strsql As String Set rs = new adodb.recordset sql = "select * from login where ID = " & _ List1.ItemData(List1.ListIndex) rs.Open sql, cn, adOpenKeyset, adLockOptimistic Text3.text = rs.Fields("firstname") Text4.text = rs.Fields("lastname") rs.Close End Sub

Search Using Like Operator Private Sub Command1_Click() Dim rs As ADODB.Recordset Dim sql as string Set rs = New ADODB.Recordset Sql = "Select * from login where firstname Like “ & _ “ ’ ” & Trim(Text1.text) & “%’ ” rs.Open sql, cn , adOpenStatic, adLockOptimistic, adCmdText List1.Clear Do Until rs.EOF List1.AddItem rs.Fields("firstname") & " " & rs.Fields("lastname") rs.MoveNext Loop rs.Close End Sub

Group Exercise Write a procedure to search for student’s name beginning with the letter “A”. Accept the student’s name using a text box Display the above records to a list box

Display records to a Combo Box Private sub form_load() sql = "select * from login" rs.Open sql, cn, adOpenKeyset,adLockOptimistic Do Until rs.EOF Combo1.AddItem rs.Fields("firstname") rs.MoveNext Loop rs.Close End sub

Combo Click Private Sub Combo1_click() Dim sql As String sql = "Select * from login where firstname = '" & Combo1.text & "'" rs.Open sql, cn, adOpenKeyset, adLockOptimistic Text8.text = rs.Fields("ID") Text1.text = rs.Fields("firstname") Text2.text = rs.Fields("lastname") Text5.text = rs.Fields("age") rs.Close

Form Unload Private sub Form_Unload(Cancel as Integer) cn.close set cn = nothing End Sub

Data Grids and Multiple Table Handling

Learning Outcomes At the end of this lecture you should be able to : Display records to a Microsoft Hierarchical Flexi Grid (MSHFGrid) Display selected records to a Microsoft Hierarchical Flexi Grid Selecting a Record on a MSHFGrid Multiple Table Handling

Key Words MSHFGrid Text Matrix EOF

References Database Access with Visual Basic 6 Jeffrey P Mc Manus SAMS Publication Visual Basic 6 Programming T Say Prentice Hall Visual Basic 6 How to Program Deitel and Deitel Chapter 18

MS HF Grid HF Grid looks like a spreadsheet with rows and columns MSHFGrid is used to display records in a presentable format MSHF Grid can be used to select an item

Procedure 1. MSHF Grid must be loaded from project / components 2. Select Project /Components and Click Microsoft Hierarchical Flexi Grid Control 6.0 Click Grid on Tool Bar and draw the Grid on the Form Write Code to display records on the grid

Displaying Records on HF Grid grid1.Visible = False - Hide the grid Dim str As String Dim rs As ADODB.Recordset Set rs = New ADODB.Recordset str = “select * from login where firstname like ‘ “ & Trim(Text1.text) & “%’ ” rs.Open str, cn, adOpenKeySet, adLockOptimistic If rs.BOF Then MsgBox “Record Not Found” Exit Sub End If

Displaying Records on HF Grid grid1.Refresh Set grid1.DataSource = rs With grid1 .TextMatrix(0, 1) = "ID" .TextMatrix(0, 2) = "Firstname" .TextMatrix(0, 3) = "Lastname" .TextMatrix(0, 4) = "DOB" .TextMatrix(0, 5) = "AGE" End With grid1.Visible = True - Show the Grid rs.close

Group Exercise Write a program to search for a student-ID from tblstudent and display the students particulars to a Data Grid. If the student ID is not found display an error message.

Display Selected Fields on HF Grid Private Sub Command2_Click() Dim rstitles as adodb.recordset Set rstitles = new adodb.recordset Dim sql ,text As String Dim row As Integer sql = “Select * from login where firstname like ‘” & Text1.text & “%’ ” rstitles.Open sql, cn, adOpenKeyset, adLockOptimistic grdtitles.Rows = 1 If rstitles.EOF Then rstitles.Close Exit Sub End If

Display Selected Fields on HF Grid Do Until rstitles.EOF row = row + 1 text = row & vbTab & rstitles.Fields("firstname") & vbTab & rstitles.Fields("lastname") grdtitles.AddItem text rstitles.MoveNext Loop rstitles.Close End Sub

Group Exercise Write a procedure to total up all the marks for each student in the student-table and display the average on a text box. Use student as the table name Use rs.recordcount to get the number of records in a table.

Selecting a Record on a Grid Private Sub grid1_Click() a = grid1.TextMatrix(grid1.row, grid1.Col) Msgbox a End Sub

Multiple Table Handling Extract data from two or more tables Used to display data to a report for printing SID S-name Age Phone Related Book ID SID Book Title

Multiple Table Handling Format : Select table1.fieldname,table2.fieldname from table1,table2 Example : Select student.name, student.id, library.title,library.bookid from student, library where student.sid = library.sid

Multiple Table Handling sql = “select login.firstname, login.lastname ,profile.title, profile.author, profile.isbn from login , profile where profile.loginid = login.id and login.id = “& txtid.text &”” rs.Open sql, cn, adOpenKeyset, adLockOptimistic grid1.Refresh Set grid1.DataSource = rs With grid1 .TextMatrix(0, 1) = "Firstname" .TextMatrix(0, 2) = "Lastname" .TextMatrix(0, 3) = "Book Title" .TextMatrix(0, 4) = "Author" .TextMatrix(0, 5) = "ISBN" End With rs.Close

Group Exercise D-ID D-Name D-Floor D-Phone Emp-ID D-ID Emp-Name Department -Table Emp-ID D-ID Emp-Name Employee -Table Write an SQL statement to access the following fields : DID, D-Name, D-Floor, Emp-ID , E-Name where a particular D-ID exists in the Employee Table

Group Exercise Write a procedure that will accept a user name and a password from two text boxes. If the user name and password is found in the database display “Valid User” otherwise display “Invalid User”. Use a MsgBox to display the appropriate message.

Search Records Between Two Dates Private Sub Command8_Click() Dim rs As ADODB.Recordset Dim sql As String Set rs = New ADODB.Recordset sql = "Select * FROM profile WHERE borrowdate between #" & Format(CDate(mskstart.text), "mm/dd/yyyy") & "#AND#" & Format(CDate(mskend.text), "mm/dd/yyyy") & "#" rs.Open sql, cn, adOpenKeyset, adLockOptimistic List1.Clear If rs.EOF Then MsgBox "RECORDS IN THAT DATE RANGE ARE NOT FOUND", vbExclamation Exit Sub End If

Search Records Between Two Dates grid1.Visible = True grid1.Rows = 1 Do Until rs.EOF row = row + 1 text = row & vbTab & rs.Fields("Title") & vbTab & rs.Fields("author") & vbTab & rs.Fields("isbn") grid1.AddItem text rs.MoveNext Loop grid1.FixedRows = 1 ‘To Write data on the First Row End Sub

Move Next – SQL statement Place a select statement in the form load to select all records. Select statement should not be placed in the move next and move previous procedure. Private sub Form_load() Dim rs1 as adodb.Recordset Set rs1 = new adodb.Recordset sql = “select * from login” rs1.Open sql, cn, adOpenKeySet, adLockOptimistic End sub

Move Next Private Sub Command5_Click() rs1.MoveNext If rs1.EOF = True Then rs1.MoveFirst End If Text8.text = rs1.Fields("ID") Text1.text = rs1.Fields("firstname") Text2.text = rs1.Fields("lastname") Text5.text = rs1.Fields("age") End Sub

Group Exercise Write a procedure to move to a previous record You need to use the following key words BOF IF….ELSE…THEN MovePrevious

Move Previous To move to a previous record rs1.MovePrevious If rs1.BOF = True Then rs1.MoveLast End If Text8.text = rs1.Fields("ID") Text1.text = rs1.Fields("firstname") Text2.text = rs1.Fields("lastname") Text5.text = rs1.Fields("age")

Group Exercise Write a program to accept a students ID ,name, age, intake and dob. Save the record to a tblstudent Write a procedure to delete a studentID Write a procedure to move to a next record Write a procedure to move to a previous record

VISUAL BASIC DATA REPORTS Bound and Unbound

Learning Outcomes At the end of this lecture you should be able to : Write a Bound Data Report to display all records for hard copy printing Write an Unbound Data Report to display selected records for hard copy printing

Key Words Data Report Bound Unbound Data Environment

Bound Data Report Is used to display records on screen for hardcopy printing Resembles like an MS-Word Document Primarily used to display all records for printing

Data Report Records Displayed Here

Bound Data Report - Step 1 Select Project Click Components

Bound Data Report – Step 2 Click Project and Click Data Environment Right Click Connection1 - Select Properties Select Microsoft Jet OLE DB Provider Click Next Select Database Path and Database Name Click Test Connection Right Click Connection1 – Add Command1 Right Click Command1 – Select Properties Select Table from Database Object Select Table Name

Bound Data Report – Step 3 Click on Command1 Tree View You will be able to see the field name Select Project – Add Data Report Drag field to the Detail Section of the Data Report Select Data Report Properties Place Command1 in Data Member Place Data Environment1 in Data Source Run Data Report In Form 1 - Private Sub Command1_Click () DataReport1.Show End Sub

Bound Data Report - Rules If database name is not selected and test connection is clicked an error message is displayed. If the previous steps are not followed the program will not run.

Unbound Data Report

Unbound Data Report Unbound data report is used to display selected fields to a data report Query statements can be written to select certain records from a table Does not depend on the Data Environment Users must write program code to display records on a data report

Unbound Data Report - Step 1

Unbound Data Report - Step 2 Insert Text Box to Detail Section1 as a field Insert Labels to Page Header - Section2 Write Code to display records to the data report

Group Exercise Write a program to accept a students ID ,name, age, intake and dob. Save the record to a tblstudent Write a procedure to delete a studentID Write a procedure to move to a next record Write a procedure to move to a previous record

Homework Write a program that will search a particular students name from <student-table> and display the Name, ID , Age on an un bound data report. The table has the following fields : Name ID Age

Homework Write a program to display all records from a table to a data report Write a program to search for a users IC Number and display his/her name, address, postcode, age , gender, tel-no to a bound data report