Transcription

Getting Started Guide8ChapterGetting Startedwith BaseOpenOffice.org’s Database Component

CopyrightThis document is Copyright 2008 by its contributors as listed in thesection titled Authors. You may distribute it and/or modify it under theterms of either the GNU General Public License, version 3 or later, orthe Creative Commons Attribution License, version 3.0 or later.All trademarks within this guide belong to their legitimate owners.AuthorsDan LewisIain RobertsMagnus AdielssonJean Hollis WeberFeedbackMaintainer: Dan LewisPlease direct any comments or suggestions about this document s the maintainer of this document, I would like to personally thankthe other authors of it. Without them, this document would not havethe quality it does. Neither would it contain as much information. IainRoberts and Magnus Adielsson offered many sound suggestions oncontent as well as format. Jean Hollis Weber with many years oftechnical writing experience has suggested many changes which havemade this document much more understandable. Special thanks alsogo to those who have translated this document into other languages sothat non-English speaking people have access to this information.Publication date and software versionPublished 13 October 2008. Based on OpenOffice.org 3.0.You can downloadan editable version of this document blished/

ContentsCopyright.2Introduction.5Planning a database.6Creating a new database.8Creating database tables.9Using the Wizard to create a table.9Creating a table by copying an existing table.14Creating tables in Design View.15Creating tables for the list box.18Adding data to the list table.19Creating a View.19Defining relationships.20Creating a database form.23Using the Wizard to create a form.24Modifying a form.28Creating forms in Design View.44Creating subforms in Design View.44Accessing other data sources.44Accessing a dBase database.45Accessing a Mozilla address book.45Accessing spreadsheets.46Registering databases created by Ooo2.x and later.46Using data sources in OpenOffice.org.46Viewing data sources.46Editing data sources.47Launching Base to work on data sources.48Using data sources in OOo documents.48Writer documents.48Calc spreadsheets.51Entering data in a form.52Getting Started with Base3

Creating queries.56Using the Wizard to create a query.56Using the Design View to create a query.60Creating reports.66Creating a static report.67Creating a dynamic report.70Modifying a report.72More ways to create reports.754Getting Started with Base

IntroductionA data source, or database, is a collection of pieces of information thatcan be accessed or managed by OpenOffice.org (OOo). For example, alist of names and addresses is a data source that could be used forproducing a mail merge letter. A shop stock list could be a data sourcemanaged through OOo.NoteOpenOffice.org uses the terms “Data Source” and “Database” torefer to the same thing, which could be a database such asMySQL or dBase or a spreadsheet or text document holdingdata.This chapter covers creating a database, showing what is contained ina database and how the different parts are used by OOo. It also coversusing the Base component of OOo to register other data sources. Adata source can be a database, spreadsheet, or text document.Data sources are only introduced in this chapter. For more detailedinformation about the use of databases, see the Database Guide.NoteOOo Base uses the HSQL database engine. All of the filescreated by this engine are kept in one zipped file. The databaseforms are included in this zipped file.A database consists of a number of fields that contain the individualpieces of data. Each table of the database is a group of fields. Whencreating a table, you also determine the characteristics of each field inthe table. Forms are for data entry into the fields of one or more tablesassociated with the form. They can also be used for viewing fields fromone or more tables associated with the form. A query creates a newtable from the existing tables based upon how you create the query. Areport organizes the information of the fields of a query in a documentaccording to your requirements.CautionIntroductionThe database in OOo requires Java Runtime Environment (JRE).If you do not have it on your computer, you can download itfrom www.java.com and install it following the instructions onthe site. It should be Java 5.0 or higher. In OOo, use Tools Options OpenOffice.org Java to register Java.Windows' version of JRE can not be used, while there are otherversions that can.5

Base creates relational databases. This makes it fairly easy to create adatabase in which the fields of the database have relationships witheach other.For example: Consider a database for a library. It will contain a fieldfor the names of the authors and another field for the names of thebooks. There is an obvious relationship between the authors and thebooks they have written. The library may contain more than one bookby the same author. This is what is known as a one-to-manyrelationship: one author and more than one book. Most if not all therelationships in such a database are one-to-many relationships.Consider an employment database for the same library. One of thefields contains the names of the employees while others contain thesocial security numbers, and other personal data. The relationshipbetween the names and social security numbers is one-to-one: only onesocial security number for each name.If you are acquainted with mathematical sets, a relational database caneasily be explained in terms of sets: elements, subsets, unions, andintersections. The fields of a database are the elements. The tables aresubsets. Relationships are defined in terms of unions and intersectionsof the subsets (tables).To explain how to use a database, we will create one for automobileexpenses. In the process, we will be explaining how a database work.Planning a databaseThe first step in creating a database is to ask yourself many questions.Write them down, and leave some space between the questions to laterwrite the answers. At least some of the answers should seem obviousafter you take some time to think.You may have to go through this process a few times before everythingbecomes clear in your mind and on paper. Using a text document forthese questions and answers makes it easier to move the questionsaround, add additional questions, or change the answers.Here are some of the questions and answers I developed before Icreated a database for automobile expenses. I had an idea of what Iwanted before I started, but as I began asking questions and listing theanswers, I discovered that I needed additional tables and fields.What are the fields going to be? My expenses divided into three broadareas: fuel purchases, maintenance, and vacations. The annual cost for6Getting Started with Base

the car’s license plate and driver’s license every four years did not fitinto any of these. It will be a table of its own: license fees.What fields fit the fuel purchases area? Date purchased, odometerreading, fuel cost, fuel quantity, and payment method fit. (Fueleconomy can be calculated with a query.)What fields fit the maintenance area? Date of service, odometerreading, type of service, cost of service, and next scheduled service ofthis type (for example, for oil changes list when the next oil changeshould be). But it would be nice if there was a way to write notes. So, afield for notes was added to the list.What fields fit the vacations area? Date, odometer reading, fuel(including all the fields of the fuel table), food (including meals andsnacks), motel, total tolls, and miscellaneous. Since these purchasesare made by one of two bank cards or with cash, I want a field to statewhich payment type was used for each item.What fields fit into the food category? Breakfast, lunch, supper, andsnacks seem to fit. Do I list all the snacks individually or list the totalcost for snacks for the day? I chose to divide snacks into two fields:number of snacks and total cost of snacks. I also need a payment typefor each of these: breakfast, lunch, supper, and total cost of snacks.What are the fields that are common to more than one area? Dateappears in all of the areas as does odometer reading and paymenttype.How will I use this information about these three fields? While onvacation, I want the expenses for each day to be listed together. Thedate fields suggest a relationship between the vacation table and thedates in each of these tables: fuel and food, This means that the datefields in these tables will be linked as we create the database.The type of payment includes two bank cards and cash. So, we willcreate a table with a field for the type of payment and use it in listboxes in the forms.TipWhile we have listed fields we will create in the tables of thedatabase, there is one more field that may be needed in a table:the field for the primary key. In some tables, the field for theprimary key has already been listed. In other tables such as thepayment type, an additional field for the primary key must becreated.Planning a database7

Creating a new databaseTo create a new database, click the arrow next to the New icon. In thedrop-down menu, select Database (Figure 1). This opens the DatabaseWizard. You can also open the Database Wizard using File New Database.Figure 1: Creating a new databaseThe first step of the Database Wizard has one question with twochoices: Create a new database or Connect to an existingdatabase. For this example, select Create a new database and thenclick Next.The second step has two questions with two choices each. The defaultchoice for the first question is Yes, register the database for me andthe default choice for the second question is Open the database forediting. Make sure these choices are selected and click Finish.NoteIf the database is not registered, it will not be accessible to theother OOo components such as Writer and Calc. If the database isregistered, other components can access it.Save the new database with the name Automobile. This opens theAutomobile – OpenOffice.org Base window. Figure 2 shows part of thiswindow.Tip8Every time the Automobile database is opened, the Automobile –OpenOffice.org Base window opens. Changes can then be madeto the database. The title for this window is always (databasename) – OpenOffice.org.Getting Started with Base

CautionAs you create a database, you should save your work regularly.This means more than just saving what you have just created.You must save the whole database as well.For example, when you create your first table, you must save itbefore you can close it. If you look at the Save icon in theStandard toolbar at the top after closing the table, it will beactive. Click the Save icon, and this icon will be grayed outagain. Not only the table has been saved, but it also been madea part of the database.Creating database tablesNoteIn a database, a table stores information for a group of things wecall fields. For example, a table might hold an address book, astock list, a phone book or a price list. A database can have fromone to several tables.To work with tables, click the Tables icon in the Database list, or useAlt a. The three tasks that you can perform on a table are in the Tasklist (see Figure 2).Figure 2: Creating tablesUsing the Wizard to create a tableCautionEvery table requires a Primary key field. (What this field doeswill be explained later.) We will use this field to number ourentries and want that number to automatically increase as weadd each entry.Creating database tables9

Since none of the fields we need for our Automobile database arecontained in any of the wizard tables, we will create a simple tableusing the wizard that has nothing to do with our database. This sectionis an exercise in explaining how the Wizard works.The Wizard permits the fields of the table to come from more than onesuggested table. We will create a table with fields from three differentsuggested tables in the Wizard.Click Use Wizard to Create Table. This opens the Table Wizard.NoteA field in a table is one bit of information. For example, in aprice list table, there might be one field for item name, one forthe description and a third for the price. More fields may beadded as needed.Step 1: Select fields.You have a choice of two categories of suggested tables: Business andPersonal. Each category contains its own suggested tables from whichto choose. Each table has a list of available fields. We will use the CDCollection Sample table in the Personal category to select the fields weneed.1) Category: Select Personal. The Sample Tables drop down listchanges to a list of personal sample tables.2) Sample Tables: Select CD-Collection. The Available fields windowchanges to a list of available fields for this table.3) Selected Fields: Using the button, move these fields from theAvailable fields window to the Selected fields window in thisorder: CollectionID, AlbumTitle, Artist, DatePurchased, Format,Notes, and NumberofTracks.4) Selected Fields from another sample table. Click Business as theCategory. Select Employees from the dropdown list of sampletables. Use the button to move the Photo field from theAvailable fields window to the Selected fields window. It will be atthe bottom of the list directly below the NumberofTracks field.5) If a mistake is made in the order as listed above, click on the fieldname that is in the wrong order to highlight it. Use the Up orDown arrow on the right side of the Selected Fields list (seeFigure 3) to move the field name to the correct position. ClickNext.10Getting Started with Base

Add/RemoveMoveFigure 3: Order of fieldsCautionBelow the Selected Fields list are two buttons: one with a , andone with a –. These buttons are used to add or to remove fieldsfrom the Selected Fields list. Be careful when using thesebuttons until well acquainted with how to create tables(Figure 3).Step 2: Set field types and formats.In this step you give the fields their properties. When you click a field,the information on the right changes. You can then make changes tomeet your needs. (See Figure 4.) Click each field, one at a time, andmake the changes listed below.Figure 4: Changing field typesCreating database tables11

NoteIf any of these fields requires an entry, set Entry required to Yes.If Entry required is set to Yes, this field must have something init. For example if FirstName has Entry required set to Yes, havingan entry with the first name missing will not be allowed. Ingeneral, only set Entry required to Yes if something must alwaysbe put in that field. By default, Entry required is set to No.CollectionID: Change AutoValue from No to Yes. AlbumTitle:–Entry required: If all of your music is in albums, change Entryrequired to Yes. Otherwise, leave Entry required as No.–Length: Unless you have an album title that exceeds 100characters in length counting the spaces, do not change thelength. Note In Base the maximum length of each field must be specified oncreation. It is not easy to change this later, so if in doubt specifya greater length. Base uses VCHAR as the field format for textfields. This format only uses the actual number of characters in afield up to the limit set. So, a field containing 20 characters willonly use space for 20 characters even if the limit is set at 100.Two album titles containing 25 and 32 characters respectivelywill use space for 25 and 32 characters and not 100 characters.Artist: Use the Default setting. And since music has authors, setEntry Required to Yes.Date Purchased: Length: default setting. Entry required should beNo. (You may not know the date.)Format: Only change the Entry Required setting: from No to Yes.Notes: No changes are required.NumberofTracks: Change the Field Type to Tiny Integer[TINYINT]. Your allowable number of tracks will be 999. SmallInteger [SMALLINT] would allow 99999 tracks if you neededmore than 999 tracks.Photo: Use the default settings.When you have finished, click Next.12Getting Started with Base

NoteEach field also has a Field Type. In Base the field type must bespecified. These types include text, integer, date and decimal. Ifthe field is going to have general information in it (for example aname or a description), then you want to use text. If the field willalways contain a number (for example a price), the type should bedecimal or another appropriate numerical field. The wizard picksthe right field type, so to get an idea of how this works, see whatthe wizard has chosen for different fields.Step 3: Set primary key.1)2)3)4)5)Create a primary key should be checked.Select option Use an existing field as a primary key.In the Fieldname drop down list, select CollectionID.Check Auto value if it is not already checked.Click Next.NoteA primary key uniquely identifies an item (or record) in the table.For example, you might know two people called “Randy Herring”or three people living at the same address and the databaseneeds to distinguish between them.The simplest method is to assign a unique number to each one:number the first person 1, the second 2, and so on. Each entry hasone number and every number is different, so it is easy to say“record ID 172”. This is the option chosen here: CollectionID isjust a number assigned automatically by Base to each record ofthis table.There are more complex ways of doing this, all answering thequestion “How do I make sure that every single record in mydatabase can be uniquely identified?”Step 4: Create the table.1) If desired, rename the table at this point. If you rename it, makethe name meaningful to you. For this example, make no changes.2) Leave the option Insert data immediately checked.3) Click Finish to complete the table wizard. Close the windowcreated by the table wizard. You are now back to the mainwindow of the database with the listing of the tables, queries,forms, and reports.Creating database tables13

Creating a table by copying an existing tableIf you have a large collection of music, you might want to create atable for each type of music you have. Rather than creating each tablefrom the wizard, you can make a copy of the original table. Each tablecan be named according to the type of music contained in it. Possiblenames could include Classical, Pop, Country and Western, and Rock,among others.1) Click on the Tables icon in the Database pane to see the existingtables.2) Right-click on the CD-Collection table icon. Select Copy from thecontext menu.3) Move the mouse pointer below this table, right-click, and selectPaste from the context menu. The Copy table window opens.4) Change the table name to Pop and click Next.5) Click the button to move all the Fields from the left window tothe right window and click Next.6) Since all the Fields already have the proper File Type formating,no changes should be needed. However, this is the time and placeto make these changes if they are needed. (See Caution belowfor the reason why.) Click Create. The new table is created.CautionCaution14Once tables have been created using the wizard and data hasbeen entered, editing them should be very limited if any editingis done at all. Fields can be added or deleted. But adding a fieldrequires taking the time to enter the data for that one field forevery record having an entry for that field. Deleting a fielddeletes all the data once contained in that field. Changing thefield type of a field can lead to data being lost either partially orcompletely. When creating a new table, it pays to create thefields with the correct names, length and format before data isadded.Tables can be deleted in a very simple way. But doing soremoves all of the data contained in every field of the table.Unless you are sure, do not delete a table.To delete a table, right-click it in the list of tables. SelectDelete from the context menu. A popup window asks if you aresure you want to delete the table. Once you click Yes, the tableand its data are gone forever unless you have a backup.Getting Started with Base

Creating tables in Design ViewDesign View is a more advanced method for creating a new table. Itallows you to directly enter information about each field in the table.We will use this method for the tables of our database.NoteWhile the Field type and formatting are different in Design View,the concepts are the same as in the Wizard.The first table to be created is Fuel. Its fields are FuelID, Date,FuelCost, FuelQuantity, Odometer, and PaymentType. FuelCost usescurrency and two decimal places. FuelQuantity and Odometer use thenumber format with 3 decimal places and 1 decimal place respectively.PaymentType uses the text format.1) Click Create Table in Design View.2) FuelID entries:a) Enter FuelID as the first Field Name.b) Select Integer [INTEGER] as the Field Type from thedropdown list. (The default setting is Text [VARCHAR].)TipShortcut for selecting from the Field Type dropdown list: use thekey for the first letter of the choice. This might require using theletter more than once to get the choice you want. You can cyclethrough the choices for a given letter by repeatedly using thatletter.After typing the name of the field in the Fields column, use theTab key to move to the Field Type column. This will enter thefield name and highlight the dropdown list. You can then use thekey for the first letter of your choice to select the field type. Justremember to use it the correct number of times if necessary.c) Change the Field Properties in the bottom section.Change AutoValue from No to Yes (Figure 5).Figure 5: Field Properties section (AutoValue)d) Set FuelID as the Primary key.Right-click on the green triangle to the left of FuelID(Figure 6).Creating database tables15

Figure 6: Primary key fieldClick Primary Key in the context menu. This places a key icon infront of FuelID.NoteThe primary key serves only one purpose. Any name can be usedfor this field. It is not necessary to use FuelID as the name of theprimary key field. We have used it so we know to which table itbelongs by its name.3) All other entries: Enter the next field name in the first column (Field Namecolumn). Select the Field Type for each field.–For Date use Date[DATE]. (Use the D key once to select it.)–PaymentType uses Text [VARCHAR], the default setting.–All other fields use Number [NUMERIC]. (Use the N keyonce to select it.) Select the Field Properties (Figure 7).Figure 7: Field Properties sectionFuelCost, FuelQuantity, and Odometer need changes in theField Properties section (Figure 7).–FuelQuantity: Change Length to 6 and Decimal places to 3.(Many fuel pumps measure fuel to thousands of a gallon inthe USA where I live.)–Odometer: Change the Length to 10 and the Decimalplaces to 1.–FuelCost: Change the Length to 5 and Decimal places to 2.Click the Format example button (Figure 7). This opensthe Field Format window (Figure 8).16Getting Started with Base

Use Currency as the Category and your currency as theFormat. My currency has two decimal places. Use what isappropriate for your currency.Figure 8: Field Format options4) Repeat these steps for each field in the table.5) To access additional formatting options, click the button to theright of the Format example panel (Format example button inFigure 7).6) Description can be anything, or can be left blank. (Figure 9 is anexample of this.)7) To save and close the table, select File Close. Name the tableFuel.Follow the same steps to create the Vacations table. The fields andtheir field types are listed in Figure 9. Make sure you make the Datefield the primary key before closing. (Right click the Grey box to theleft of Date. Select Primary key from the context menu.) Name thetable Vacations, and save it.Creating database tables17

Figure 9: Example of Description entriesCreating tables for the list boxWhen the same information can be used in several fields, design atable for each type of information. Each table will contain two fields:the information field, and ID in this order.CautionYou must create these tables with the information field listedfirst and the and the ID field listed last. Failure to do so willproduce the wrong results. For my Payment table, I use Nameand ID as my fields, with Dan, Kevin, and Cash being the Nameentries. The corresponding ID entries are 0, 1, 2. When theName field is listed first in the table, one of the three nameswill appear in the payment field of the Fuel table. If the ID fieldis listed first, 0, 1, or 2 appear in the payment field instead.1) Follow the directions in “Creating tables in Design View” on page15. In the table we will create, the two fields can be Type andPaymentID. Make sure that the AutoValue is set to Yes for thePaymentID field. Set the PaymentID field as the primary key. (SeeFigure 10.)2) Save the table using the name Payment Type.18Getting Started with Base

Figure 10: Table in Design ViewNote:If you have several tables to create with the same fields, designone table and produce the other tables by cutting and pasting.(See “Creating a table by copying an existing table” on page 14.)Adding data to the list tableList tables do not require a form. Instead, add their data directly to thetable. In this example, use the names of the two people with a bankcard and Cash for cash purchases.1) In the main database window, click on the Tables icon (Figure 2).Right-click on Payment Type and select Open from the contextmenu.a) Enter Dan in the first row. Use the tab key to move to thesecond row.b) Enter Kevin in the second row.c) Enter Cash in the third row.2) Save and close the table window.TipThe Enter key can also be used to move from field entry to fieldentry. For this example, enter Jan. in the first Name field. Entermoves the cursor to the ID field. Enter then moves the cursor tothe second Name field.The Down Arrow key can also be used to move from row to row.NoteThe PaymentID field contains AutoField until you use theEnter key to move to the second row. Then it becomes a 0. Asyou add the entries to each row, the rows of the PaymentID fieldchange to consecutive whole numbers. For example the firstthree numbers in this field are 0,1,2.Creating a ViewA View is a query. Because of this, the details of how to create and usea View are in the Creating queries section.Creating database tables19

Figure 11: View of some fields from the Vacations tableA View is also a table. Its fields come from the fields of one or moretables of the database. It provides a way to look at a number of fieldswithout regard to the table to which any of the fields belong. A Viewcan consists of some of the fields of one table as in Figure 11. Or, it canconsist of fields from more than one field as in Figure 12.Figure 12: View of fields from the Fuel and Payment Type tablesCautionData can not be entered into a View like it can be added to atable. It is strictly for viewing data which has already beenentered into the table.Defining relationshipsNow that the tables have been created, what are the relationshipsbetween our tables? This is the time to define them based upon thequestions we asked and answered in the beginning.When on vacation, we want to enter all of our expenses all at one timeeach day. Most of these expenses are in the Vacations table, but thefuel we buy is not. So, we will relate these two tables using the Datefields. Since the Fuel table may have more than one entry per date,this relationship between the Vacations and Fuel

registered, other components can access it. Save the new database with the name Automobile. This opens the Automobile – OpenOffice.org Base window. Figure 2 shows part of this window. Tip Every time the Automobile database is opened, the Automobile – OpenOffice.org Bas