Você está na página 1de 4

Maria Cheska M.

Juatchon
BSCS - 3

A Data Control Language (DCL) is a computer Many VB controls are "data-aware", and can be "bound" to
the Data Control. That is, as you move from record to
language and a subset of SQL, used to control access record using the Data Control, the bound controls show
to data in a database. you the field contents of each record. Bound controls
Examples of DCL commands include: generally have a DataSource property, which should be
the name of the Data Control, and a DataField property,
• GRANT to allow specified users to perform which is the name of the field you want displayed in that
specified tasks. control.
• REVOKE to cancel previously granted or
denied permissions. Creating a Database
The following privileges can be GRANTED TO or Visual Basic uses the Microsoft Access database engine.
REVOKED FROM a user or role: Use Microsoft Access to create a new database, or use
the Data Manager application provided with Visual Basic.
• CONNECT You can launch Data Manager directly from VB, from the
• SELECT Add-Ins menu.
• INSERT You can also use databases created with dBase III, dBase
IV, FoxPro 2.0 or 2.5, Paradox, Btrieve, Excel, or any
• UPDATE ODBC-registered source. To use an option other than
• DELETE Access, you need to set the Connect property for the Data
Control. For details, search Visual Basic's Help file for the
• EXECUTE Connect Property.
• USAGE
Office 2000 note:
InOracle, executing a DCL command issues an implicit Visual Basic is not easily compatible with Access 2000's
commit. database format. If you create a database using Access
2000, one of the menu items in Access is "Save As
In PostgreSQL, executing DCL is transactional, and can Previous Version". Use that to save in Office 97 format.
be rolled back.
There IS a way to open Access 2000 databases in VB, but
Reference:http://en.wikipedia.org/wiki/Data_Cont it involves extra code that will make these first two
rol_Language database lessons more cumbersome. For those who need
the secret, the notes are at the very bottom of this page.
The Visual Basic 6.0 Data control is used as a
mechanism for binding controls to a database using DAO.
Visual Basic 2005 has no equivalent for the Data control;
Trying to use Visual Data Manager
the data-binding architecture has changed and DAO is no Note: the Data Manager that came with VB3 had a few
longer supported. For more information, see Data flaws. Microsoft did a much better job with the new Data
Manager in VB4. However, they seem to have lost their
Access for Visual Basic 6.0 Users. minds with the VB5 version. Its interface is "interesting", to
The Data control also provides an interface for navigating put it most mildly.
data, with buttons for moving back and forth through rows
1. Launch Visual Data Manager from the VB Add-
in a database table. Visual Basic 2005 has an equivalent
Ins menu.
control, the BindingNavigator control, which also 2. Choose File/New..., choose Access 7.0, and give
contains buttons for adding and deleting rows. the new database a name.
Reference:http://msdn.microsoft.com/en- 3. Right-click in the Database Window. (There
us/library/tw9xakbf%28VS.80%29.aspx appears to be no other way to do this, nor any
instructions that would lead you to this. I
accidentally found it when I was about to give
The Visual Basic Data Control can be used to write up!) Click New Table in the pop-up menu. In the
VB programs that can easily manipulate databases resulting dialog box, give the new table a name.
created with Microsoft Access, FoxPro, dBase, Paradox, 4. Click the Add Field button. Enter a field name and
Btrieve, Excel, or any ODBC*-compliant database, such field type. Click the Okay button to add the new
as Oracle and SQL Server databases. (*Open DataBase field to the list. Keep repeating for a few more
Connectivity). Visual Basic's native database format is fields. When done, click Close to stop adding
Access, and the Access "Jet" Database Engine is included fields and then close the table dialog.
with VB.
5. In the Database Window, you'll see the name of
The Data Control has two key properties: DatabaseName your new table. Double-click to open the table so
is the filename of a compatible database. RecordSource is you can add records to the table. (That was
the name of a table in the database, or the result of a SQL obvious, wasn't it? Again there appears to be no
(Structured Query Language) query. other way to get to this point. If you single-click,
you just see a list of properties that are mostly
meaningless to you at this point.) You can come The RecordSource can be the name of a table in a
back and add more records any time. database, the name of an Access database query, or the
6. Exit VisData. You now have a database file. text of a SQL query. If you change the RecordSource at
Phew! run-time, you must use the method Data1.Refresh to
actually go out and get the data and assign it to the
RecordSet.
Quick Start with the Data Control
Once you have a RecordSet, you can use the following
methods in your program:
1. To use a Data Control, first select the
control from the toolbox and draw it on your form. RecordSet Methods
Its default name is Data1, which we'll use in the Data1.RecordSet.AddNew
examples below. adds a new record to the recordset
Data1.RecordSet.Delete
2. In the properties window, set the DatabaseName deletes the current record
property to the filename of the database you Data1.RecordSet.MoveNext
want. Click on the ellipsis button (...) to use a "file moves to the next record in the recordset
open" dialog. Data1.RecordSet.MovePrevious
3. Set the RecordSource property to the name of a moves to the previous record
database table within the database you selected. Data1.RecordSet.MoveFirst
If you've already selected a database as in step moves to the first record
2, a drop-down list of choices will be provided. Data1.RecordSet.MoveLast
4. Put a Text Box on your form. (You can also use moves to the last record
other data-aware controls, such as CheckBoxes, Data1.UpdateRecord
Labels, Image controls, and PictureBoxes.) saves a changed record. This is also done
5. Set the DataSource property for the text box to automatically when you use any of the Move
Data1. methods. With VB6, this is also done automatically
when the control is unloaded (when your
6. Set the DataField property for the text box to the application exits).
field you wish to display. If steps 2-5 have been
accomplished with a valid database, a drop-down
list of choices will be provided. RecordSet Properties
7. You may wish to put a Label control in front of the Data1.RecordSet.EOF
text box with the fieldname selected in step 6. True if MoveNext has moved us past the last
8. Repeat steps 4-7 for each field you wish to record
display. Data1.RecordSet.BOF
9. Run your application. True if MovePrevious has moved us in front of the
first record
Another Way: Grid View Data1.RecordSet.RecordCount
The number of records in the RecordSet. This is
accurate with small RecordSets. For large
1. Start a new project and put a Data RecordSets you may have to perform a MoveLast
Control on the form to get this actual value.
Data1.RecordSet.AbsolutePosition
2. Set the DatabaseName property of Data1 The number of the current record in the RecordSet.
Starts at zero. This property does not appear to be
3. Set the RecordSource property reliable in VB6. I put code to display this in the
Data Control's Reposition event, and sometimes it
4. From the Project menu, choose Components. worked, sometimes it gave odd results.
Check either the Microsoft FlexGrid control or the Data1.RecordSet!fieldname
Microsoft DataBound Grid control. The FlexGrid The contents of a specific field in the current record
is read-only, but it has features such as data- of the RecordSet. Replace fieldname with the valid
pivoting. The DataBound Grid control allows the name of a field.
user to edit its fields.

5. Put a DBGrid or FlexGrid control on your Yet Another (Bad) Way to Get Started:
form. Make it fairly large. The Dataform Designer
6. Set the DataSource property of the grid to Data1 Visual Basic 4 provided one other way to generate the
beginning of a database application: the Dataform
7. Run your program Designer. It automatically creates a form, similar to what
we created with the first example, and includes some code
Have you noticed that we have yet to write ANY code?
for adding and deleting records. However, you should plan
to make some code modifications if you use this.
The Data Control's RecordSource and In Visual Basic 5, they've taken this component and put it
RecordSet Properties in .... VisData. Yikes! Read on to the last paragraph of this
section before you spend a lot of time with this: the code
The RecordSource tells where the data will come from.
generated by Dataform Designer has serious flaws in both
You can think of the Recordset property as the actual data
VB4 and VB5!
that you've requested using the RecordSource.
1. From the Add-Ins menu, choose Visual Data use an alternate method for adding a new record.
Manager again.
2. In Visual Data Manager, choose File/Open The code below assumes you have Command Buttons for
Database, and open a database file, such as the Add and Delete.
one you created a few minutes ago. Private Sub cmdAdd_Click()
3. In the Utility menu, choose DataForm Designer... ' Add a blank record and save it so it is the current
4. Fill in a name for your form at the top of the record. It gets put at the end.
Dataform Designer dialog, and set the Data1.RecordSet.AddNew
RecordSource to a (the) table in your database. ' Put code here if you have required fields in your
5. Click the >> button to add all fields to this form. database. Assign default values.
6. Click on Build the Form. When it is done, Close Data1.UpdateRecord
the dialog. Data1.Recordset.MoveLast
If you set this form to be your startup form (in VB5, Project End Sub
menu/Project Properties/General/Startup Object), you can
now run the program! Private Sub cmdDelete_Click()
Data1.RecordSet.Delete
If you inspect the code, you will find that the Dataform ' Now attempt to move forward to a valid record:
Designer created event procedures for clicking each of the Data1.RecordSet.MoveNext
five command buttons, plus procedures for the events ' But if we just deleted the Last record, we need to move
Data1_Error, Data1_Reposition, and Data1_Validate. back instead:
Unfortunately, their code allows the user to easily crash If Data1.RecordSet.EOF Then
the program, and the Update button is very misleading. Data1.RecordSet.MovePrevious
(Update usually occurs whether you click it or not!). I ' Now check to see if we've moved off the front...
recommend deleting the Refresh and Update buttons, ' if so, we've just deleted the ONLY record! So add a
altering the code for the cmdAdd and cmdDelete click new one...
events, and adding Form_Load and Form_Unload events. If Data1.RecordSet.BOF Then
The recommended code is given a few sections below. Data1.RecordSet.AddNew
Data1.UpdateRecord
Data1.Recordset.MoveLast
Data Control Events: Error, Reposition, End If
Validate End If
The Error event handles any error that occurs with the End Sub
database. Use this event to code what you want to happen
when an error occurs. Private Sub Form_Unload()
' add the following to Form_Unload to make sure any
The Reposition event occurs when the user moves to last changes are saved:
another record in the RecordSet. Data1.UpdateRecord
End Sub
The Validate event occurs prior to updates, either
because of moving to another record or explicitly asking
for an update to occur. Use this event to do any validation This "UpdateRecord" in the Form_Unload event may not
on any of your form fields prior to writing to the database. be necessary in VB6. In earlier versions it was needed,
If a field is invalid, you can cancel the update and the but the VB6 Data Control appears to automatically update
action that caused it by setting Action=0 and Save=False. the last record when you exit the program.
If you have an Exit button, or a File menu with the Exit
Basic Code for the Data Control option (you should!), you should use the line "Unload Me"
to exit your program. In earlier programs it did not matter if
Although browsing and editing require no code, you must we used the other choice: "End". Now it does.
write code to add and delete records. Furthermore, you
should add a couple lines of code in your Form_Load
event to avoid an empty Recordset. DatabaseName and Form_Load
A problem that has plagued VB from the original database There are two things you should add to Form_Load. First,
version is how it handles "no current record". There are when you are done editing the properties of the controls
several situations where your "form" can be blank. It on your form, you should go back to the Data Control and
appears to be an empty record or a record in which you set the DatabaseName property to blank. While setting the
can enter data, but it isn't! There's no current record DatabaseName property makes it convenient at design-
displayed. Information you type won't be saved, and trying time (table and field names in the database automatically
a "delete" will crash your program. It's important to avoid show in drop-down lists), the path and filename for the
those situations. database get written to your EXE file unless you clear
DatabaseName. If your database is in a directory called
Before VB6, when adding a record, if you didn't "C:\VBPROGS\DATATEST", when you install your EXE on
immediately UpdateRecord, the user could crash the someone else's machine, it will look on their hard disk for
program by clicking Delete. They changed that in VB6. that same directory name!
Now the program doesn't crash.... instead you wind up
deleting some other record! The better way is to clear DatabaseName prior to making
your EXE, install your database file into the same directory
Here is safe code for adding and deleting. The only issue as your EXE file, and use App.Path to set the
you may have is if your database has required fields. DatabaseName at run-time.
Before you use the UpdateRecord command, you should
assign default data to those fields. Otherwise, you must The following code for Form_Load does that. It assumes a
database file named "MYDATA.MDB". Use whatever is Set Data1.Recordset = rs
appropriate. The one other check made by Form_Load is
that the RecordSet is not empty. If it is, a new record is Note: If you choose this method, you will also have to use
added. rs.Close and the last two lines (Set rs... and Set Data1...)
Private Sub Form_Load() when you use SQL queries in the next database lesson.
Dim DBPath as String
Reference:http://graphicsmagician.com/vbcourse/07
DBPath = App.Path
If Right(DBPath,1) <> "\" Then DBPath = DBPath & "\" datacontrol/data1.htm
Data1.DatabaseName = DBPath & "mydata.mdb"
Data1.Refresh

If Data1.RecordSet.EOF Then
Data1.RecordSet.AddNew
Data1.UpdateRecord
Data1.Recordset.MoveLast
End If
End Sub

More Database Programming Tips


Accessing data directly, without a bound control:
Dim s as String
' assign the value of a ZipCode field to s:
s = Data1.Recordset!ZipCode

Looping through the whole recordset:


' Perform some operation on every record in the
recordset
Data1.Recordset.MoveFirst
Do While Data1.Recordset.EOF = False
' Insert your code here to do whatever to this
record:

Data1.Recordset.MoveNext
Loop

Office 2000 notes (only for those who absolutely


need to know how to do this. Otherwise, ignore.)
To use an Access 2000 database (if you choose not to
"Save As Previous Version" in Access), you should do the
following:
(1) Under Project/References in Visual Basic, click on
Microsoft DAO 3.6, and de-select any previous version of
the DAO (Data Access Object).
(2) In General Declarations, add the following:
Private db As Database, rs As Recordset

(3) Do NOT set the DatabaseName property of the Data


Control.
(4) In Form_Load, add the following:
Set db =
DBEngine(0).OpenDatabase("mydatabase.mdb")

'replace mydatabase with the path and name of your


Access 2000 mdb file

Set rs = db.OpenRecordset("mytable")

' replace mytable with the name of a table in your


database

Você também pode gostar