C#Builder and InterBase ADO.NET Tutorial by Clay Shannon

Par: Clay Shannon

Résumé: Create a simple ADO.NET app with a parameterized query using C#Builder and InterBase

Most developers write database applications--either all the time, on a regular basis, or at least on occasion. In this tutorial, we will walk through the creation of a simple ADO.NET application using C#Builder and InterBase.

This application will display information about Borland's TeamB. The user will be able to select a Borland tool and see which TeamB members support that tool.

For a simple application like this, we could put all the data into one table, with only two fields, like this:

TEAMB
Name (PK)
Tool

But doing it that way would violate the relational database normalization rule which outlaws repeating (redundant) data, as the same values would appear multiple times in the Tool column. In fact, it's even theoretically possible that TeamB members in the future could support more than one tool-in which case the name would be improperly duplicated in the table. Additionally, the above "quick and dirty" table design would violate each column having atomic data, as the first name and last name are bundled together in the first column.

So, we will bite the bullet and "do it right" instead by creating three tables, as follows:

TEAMB_MEMBERS
TeamB_ID (PK)
FirstName
LastName

TEAMB_TOOLS
Tool_ID (PK)
ToolName

TEAMB_MEMBERS_AND_TOOLS
TeamB_ID (FK)
Tool_ID (FK)

The first two tables are lookup tables, and the third and last one is a many-to-many table merging the two lookup tables. Why do we need a many-to-many table? Because there are many TeamB members for each tool, and it's possible that there will be many tools for a given TeamB member some time in the future. The two foreign keys in the many-many table comprise that table's (composite) key.

The ID columns will be integers; the others will be strings.

Follow these steps to create the database and its tables:

  1. Open IBConsole (if you don't have IBConsole installed, get it here: http://codecentral.borland.com/codecentral/ccweb.exe/listing?id=19220
  2. Select Local Server in the left pane
  3. Right-click and select Login
  4. Enter the appropriate password (by default-that is, until and if you change them-the InterBase username is SYSDBA and the password is masterkey)
  5. Select Database | Create Database

The Create Database dialog will display. Enter "TeamB" in the Alias edit box, and "C:TeamB_DatabaseTeamB.gdb" in the first row beneath the Filename(s) column, like this:

This adds a database named TeamB beneath Local Server | Databases in IBConsole's left pane.

6. Select Tools | Interactive SQL

7. In the SQL window in the top pane, enter:

CREATE TABLE TEAMB_MEMBERS
(TEAMB_ID INTEGER NOT NULL,
FIRST_NAME VARCHAR(32) NOT NULL,
LAST_NAME VARCHAR(32) NOT NULL,
CONSTRAINT TEAMB_ID_PK PRIMARY KEY (TEAMB_ID)
)

8. Select the "Execute Query" icon on the toolbar (lightning bolt with question mark) to create the table.

9. Enter the following in the SQL window in the top pane:

CREATE TABLE TEAMB_TOOLS
(TOOL_ID INTEGER NOT NULL,
TOOL_NAME VARCHAR(32) NOT NULL,
CONSTRAINT TOOL_ID_PK PRIMARY KEY (TOOL_ID)
)

10. Select the "Execute Query" icon on the toolbar.

11. Enter the following in the SQL window in the top pane:

CREATE TABLE TEAMB_MEMBERS_AND_TOOLS
(TEAMB_ID INTEGER NOT NULL,
TOOL_ID INTEGER NOT NULL,
FOREIGN KEY (TEAMB_ID) REFERENCES TEAMB_MEMBERS (TEAMB_ID),
FOREIGN KEY (TOOL_ID) REFERENCES TEAMB_TOOLS (TOOL_ID)
)

12. Select the "Execute Query" icon on the toolbar.

IBConsole will now appear like this:

If you 2-click the individual tables, a property dialog will display replete with Properties, Metadata, Permissions, Data, and Dependencies tabs for the table.

Now, we need to populate the tables with data. We could write a quick-and-dirty GUI app (in C#Builder, Delphi, or some other tool) to do this, but with the (low) volume of data we're working with, it's just as easy-nay, easier-to simply enter the data directly into IBConsole. You can either enter the following data, or download the tables from CodeCentral (http://codecentral.borland.com/codecentral/ccweb.exe/listing?id=20304).

To enter the data yourself, follow these steps:

  1. 2-click TEAMB_MEMBERS in IBConsole
  2. Select the Data tab
  3. Enter the values from http://info.borland.com/newsgroups/teamb/teambbyname.html Add an integer ID value starting at 1 for each member, proceeding in last-name alpha order (1 for Yorai Aminov, 2 for Jim Bailey, etc.)
  4. 2-click TEAMB_TOOLS
  5. Select the Data tab
  6. Enter the following values:
  7. TOOL_ID

    TOOL_NAME

    1

    Delphi

    2

    Interbase

    3

    C++Builder

    4

    JBuilder

    5

    C#Builder

    Note: As of the time of writing, there are no C#Builder TeamB members, as it is a new product and no C#Builder gurus have asserted themselves (so to speak) yet. Maybe you, dear reader, will end up being one of these august elect few.

  8. 2-click TEAMB_MEMBERS_AND_TOOLS
  9. Select the Data tab
  10. Enter the following values:

TEAMB_ID

TOOL_ID

1

1

2

3

3

3

4

1

5

1

6

3

7

1

8

1

9

3

10

3

11

1

12

4

13

4

14

1

15

4

16

4

17

4

18

3

19

1

20

1

21

3

22

3

23

3

24

4

25

4

26

3

27

1

28

1

29

4

30

4

31

1

32

2

33

1

34

2

35

1

36

2

37

1

38

3

39

1

40

1

41

3

42

4

 

CREATING THE C#BUILDER APP TO VIEW THE DATABASE

Now we'll create the C#Builder ADP.NET app to view the TeamB data. As this is more-or-less a "proof of concept" application, as opposed to a full-fledged demonstration of C#Builder's database capabilities, this app will present read-only views of the data. To code along, follow these steps:

  1. Start up C#Builder if you haven't already done so, and select File | New | C# Application or click the New on the Welcome Page. In the New Items dialog, the C# Project folder should be selected (if not, select it). Select Application in the right pane and then select the OK button.
  2. In the New Application dialog, change the Name of the project from its default value to TeamB.
  3. Select the ellipsis button to the right of the Location edit, and save the project wherever you want (or allow it to save to the default location). For the sake of simplicity, you might want to save your source code in the same directory as the TeamB database.
  4. Select the OK button.
  5. Change the Text property of the form (found beneath the Appearance category) to "TeamB-o-rama" or something equally suave and debonair.
  6. Select the Data Explorer tab, which is by located by default in the Northeast corner of the IDE.
  7. Right-click the InterBase Provider node and select Add New Connection.
  8. Enter TeamB in the Connection Name edit:
  9. Select the OK button.
  10. Expand the InterBase Provider. You should have two InterBase aliases set up: IBConn1 (created by default when you installed C#Builder), and the new TeamB alias.
  11. Select the new TeamB alias, right-click and select Modify Connection.
  12. Beneath the Connection category, click the ellipsis buttons for the Database property, and navigate to the location of TeamB.gdb
  13. The Connections Editor dialog should now look something like this:
  14. Select the Test button to verify that it responds with a "Connection Successful" message.
  15. If you expand the TeamB connection, and then Tables, and then each of the three tables, you will see this:

If you 2-click a table name, the contents of the table will display in the IDE (very nice feature).

Now to hook up some components, both visual and non-. Follow these steps:

  1. Drag the TEAMB_MEMBERS table from the Data Explorer to the form. This will cause two non-visual components to be placed in a logical receptacle below the form (out of the way of the form, which is another nice feature of the new IDE). These two components are bdpConnection1 and bdpDataAdapter1.
  2. Click the bdpConnection component to highlight it.
  3. Right-click the bdpConnection component and select Connection Editor from the context menu (or select the hot label at the bottom of the Object Inspector) and verify that the Connection it is set to is indeed TeamB.
  4. Click the bdpDataAdapter component and either right-click and select Configure Data Adapter from the context menu, or select the Configure Data Adapter hot label beneath the Object Inspector.
  5. Verify that New Data Set is selected on the Data tab and select the OK button. This will create DataSet1 and add it to your menagerie of non-visual components at the bottom of the form.
  6. Set the bdpDataAdapter's Active property (beneath the LiveData property category) to True.
  7. Type "co" into the search edit beneath the Tool Palette. Drag a ComboBox component from the Windows Forms category onto the form, and place it at the upper left of the form.
  8. Type "bu" into the search edit beneath the Tool Palette. Drag a Button from the Windows Forms category onto the form, to the right of the combo box.
  9. Change the button's Appearance.Text property to "Filter".
  10. Type "da" into the search edit beneath the Tool Palette. Drag a DataGrid from the Data Controls component category onto the form.
  11. Size the data grid to take up most of the remainder of the form.
  12. Select the Data Grid component, and beneath the Data category, set Data Source to DataSet1, and Data Member to Table1. You will now see the contents of the TEAMB_MEMBERS table in the grid.
  13. Select the ComboBox, and select the ellipsis button to the right of the Items property (Data category). The String Collection Editor displays.
  14. After entering the following values, select the OK button:
  15. Delphi
    Interbase
    Jbuilder
    C++Builder
    C#Builder

  16. Change the combo boxes Appearance.Text property to an empty string. The form now looks something like this:
  17. With the bdpDataAdapter component highlighted, select the Configure Data Adapter component editor context menu item or hot label again.
  18. In the Data Adapter's component editor, deselect the Insert, Update, and Delete SQL commands.
  19. Enter the following in the SQL pane for the Select statement:
  20. 
    SELECT DISTINCT M.FIRST_NAME, M.LAST_NAME 
    FROM TEAMB_MEMBERS M, 
    TEAMB_MEMBERS_AND_TOOLS A
    WHERE M.TEAMB_ID = A.TEAMB_ID
    AND A.TOOL_ID = ?
    ORDER BY M.LAST_NAME
    

    The "?" mark in the query above is C#Builder's way of denoting a parameter in the query (in Delphi, a colon is used for parameterized queries; a question mark actually makes more sense, though).

  21. Select the dbpDataAdapter component and then click the ellipsis button in the Object Inspector to the right of the Fill.SelectCommand.Parameters property.
  22. In the bdpParameter Collection Editor dialog, select the Add button.
  23. From the Data.dbType dropdown, select the Int32 data type.
  24. Enter "ToolID" in the Misc.ParameterName edit and select the OK button.
  25. You might want to select the component editor's Preview Data to perform a "sanity check" on your SQL statement. To do so, though, first change the "?" in your SQL statement temporarily to any value between 1 and 4 (inclusive) to see which TeamB members are assigned to the various tools. Select the Refresh button to display the data. After convincing yourself of your SQL code's validity, change the TOOL_ID value in the SQL statement back to "?".
  26. Select the OK button to close the component editor.

Now we need to add the code that will assign the value to the parameter at run-time. 2-click the Button and the following code its Click event:


private void button1_Click(object sender, System.EventArgs e)
{
  bdpSelectCommand1.Close();
  bdpDataAdapter1.Active = false;
  bdpSelectCommand1.Parameters["ToolID"].Value =
    this.comboBox1.Items.IndexOf(this.comboBox1.Text)+1;
  bdpDataAdapter1.Active = true;
}

Now when you run the app, select Delphi from the combo box, and click the button, you will see the following:

Voila! With a measly four lines of code, we've created a handy little ADO.NET app that uses InterBase and a parameterized query to keep tabs on which tools those 100-lb.-head TeamB members voluntarily support. It only gets better from here.

Note: Although it is true that in this particular demo app the TEAMB_TOOLS table wasn't used, it is a useful table to have in this database for other apps that may make use of TeamB personnel information. In a slightly more complicated app, the items in the combo box could be dynamically populated with the contents of that table.

The usefulness of this application could be enhanced by adding fields to the TeamBMembers table to hold each guru's email address and website URL. You could also write code to periodically check the TeamB web site and add any new members or tools to the tables. These possible enhancements are, as you probably surmised, an exercise left for the reader.

<bio>

Clay Shannon is a Borland and PDA-certified Delphi developer and the author of "Tomes of Delphi: Developer's Guide to Troubleshooting" (Wordware, 2001) as well as the novel he claims is the strangest one ever written, "the Wacky Misadventures of Warble McGorkle" (see Wacky Warble, etc. for more information on the 4 Novels application, which contains this and three other novels he has penned).

You can find out more about Clay at: http://hometown.aol.com/bclayshannon/myhomepage/index.html
You can look into Clay's shareware and determine his current availability at:
http://hometown.aol.com/bclayshannon/myhomepage/business.html
You can contact him at:
BClayShannon@aol.com

Réponse serveur de: ETNASC02