Download presentation
Presentation is loading. Please wait.
Published byCassandra Horn Modified over 5 years ago
1
Kurtis D. Leatham KDL@KomputerMan.com http://www.KomputerMan.com
Databases & SQL Basics Kurtis D. Leatham
2
About Me I own KomputerMan.com, a 1 employee Cold Fusion and Flex application development consulting company. Developing CF applications since 1998 and have been consulting since 1999. Developed my first Flex App this year. I am not one of those people who delves into how CF does its magic. I am much more concerned with how I can use CF to make my own magic! June 27th- 30th 2007
3
Introduction Database access is easy with CF
Just need to learn a few basics about databases, SQL, and some CF Some CF experience is presumed, not critical Most of the CF used is easy to pick up Some old school some new school Many topics are not CF specific May apply to any DBMS All examples work with MS Access and CF and are available for download. June 27th- 30th 2007
4
Today’s Agenda Databases, SQL Basics, and ColdFusion
Working with Databases in CF Databases, Datasources, CFC's Database basics CF and SQL Basics Creating queries Build dynamic SQL statements Displaying query results Interact with a database CF Forms and SQL Insert and select data with a CF Form Q&A June 27th- 30th 2007
5
DB Management Systems DBMS A DBMS is software that organizes databases
Jill Jack Pets DBMS CFML Server A DBMS is software that organizes databases Access is both a DBMS and a database Doesn't have to run on the CF server Databases are the heart of business apps Either you have one, or will create one Creating databases is beyond scope of class June 27th- 30th 2007
6
DB Management Systems Jill Jack CFML Server SQL Data Pets ODBC Drivers communicate with DB via SQL commands CF uses “Datasources” to refer to the ODBC Drivers SQL stands for Structured Query Language June 27th- 30th 2007
7
Database Basics Pets PetTypes People 2 1 PeoCnt (Identity) Jack Frost 12/31/1848 Santa Clause BirthDate (Date) FName (Text 20) LName (Text 30) 11/24/1863 A Database is a collection of data, hopefully stored in an organized fashion Composed of tables Tables are organized in rows and columns Each column is assigned a Datatype to define the type of data that the column can hold Datatype examples: text, date, currency, etc… Each Row contains data June 27th- 30th 2007
8
Database Basics 2 1 PeoCnt (Identity) People Jack Frost 12/31/1848 Santa Clause BirthDate (Date) FName (Text 20) LName (Text 30) 11/24/1863 Pets PetTypes Tables are Similar to a spreadsheet but a Table IS NOT a spreadsheet Tables should describe one thing and one thing ONLY I.E. A persons name, address, birth date, etc… Not a persons name and the name of their dog(s) June 27th- 30th 2007
9
Primary Keys 2 1 PeoCnt (Identity) People Jack Frost 12/31/1848 Santa Clause BirthDate (Date) FName (Text 20) LName (Text 30) 11/24/1863 Each row in the table should be uniquely identified with a Primary Key (PK) A PK is not required, but I won't build a table without one Recommendation: Use an Auto Incrementing field as your PK Concatenated (two or more fields together) Keys work but are a pain!!! June 27th- 30th 2007
10
Primary Keys No two rows can have the same primary key value
Each row must have a primary key value (no nulls) Null: Column having no value at all Not the same as space or empty string June 27th- 30th 2007
11
Our Example Database Simple application that tracks people and their pets One person can have multiple pets One pet can only be associated to one person (my business rule here) Each pet must have a type such as Dog or Cat June 27th- 30th 2007
12
Our Example Database PeoCnt is the PK for the People table
PeoCnt is a Foreign Key in the Pets Table PetCnt is the PK for the Pets table PetTypeCnt is the PK for the PetTypes table PetTypeCnt is a Foreign Key in the Pets table June 27th- 30th 2007
13
Datasources A Datasource is the CF name for the DB
Pets DBMS: MS Access DB Name: Pets Filename: Pets.mdb Datasource Name: Pets_DB A Datasource is the CF name for the DB Describes the name, physical location, and ODBC driver for connecting to DB Can choose any name, unique to CF Server June 27th- 30th 2007
14
Datasources Defined and Created by the CF Admin
Can use OBDC driver or CF JDBC Drivers Various parameters can be set, to affect performance and features Can store the username and password SQL operations can be restricted (read only) BLOBs can be enabled See CF Administrator manual for details June 27th- 30th 2007
15
Datasources Use CF Administrator to create the 'Pets_DB' DSN
In CF Admin click on Data & Services Click on Data Sources Fill in the blanks then hit the Add button June 27th- 30th 2007
16
Datasources Locate the database Hit the Submit button
June 27th- 30th 2007
17
Selecting Data with SQL
The SELECT query is most frequently used query Retrieves data from one or more tables But only 1 datasource At a minimum a SELECT query takes two clauses The data to be retrieved (SELECT clause) The table where the data resides (FROM clause) May also specify Filtering conditions (WHERE clause) Sort order (ORDER BY clause) Can use Joins to link tables together (JOIN or WHERE clause) June 27th- 30th 2007
18
Simple Select Statement
SELECT FName, LName, City FROM People Example 1 Specify the columns to be retrieved Must specify at least one column Can retrieve all columns in a table with SELECT * Recommendation:Specify the needed columns Some databases may require table names to be fully qualified with a prefix indicating the table name People.FName June 27th- 30th 2007
19
Datasources Part II <CFQUERY> used to create queries
<CFQUERY DATASOURCE=“Pets_DB” NAME=“GetPeople”> SELECT FName, LName, City FROM People </CFQUERY> <CFQUERY> used to create queries DATASOURCE indicates the DSN to use NAME provides a name for the record set that you will be using somewhere else in your code Can pass any SQL that’s acceptable to the DBMS inside the CFQUERY Tags DSN contains Username and Password to connect to the database if needed June 27th- 30th 2007
20
Datasources Part II Set up a Request variable for your DSN
<CFSET Request.DSN = 'Pets_DB'> As set inside Application.cfc. <CFQUERY DATASOURCE=“#Request.DSN#” NAME=“GetPeople”> SELECT FName, LName, City FROM People </CFQUERY> Set up a Request variable for your DSN The Request variable gets set in Application.cfc If the Datasource ever changes you just make one change in Application.cfc and you are finished June 27th- 30th 2007
21
Displaying Query Results
<CFOUTPUT> can be used to display the record set To show the first record <CFOUTPUT> #GetPeople.FName[1]#, #GetPeople.LName[1]# </CFOUTPUT> To show all records of the record set <CFOUTPUT QUERY="GetPeople"> #FName#, #LName#, #City#<BR> </CFOUTPUT> June 27th- 30th 2007
22
Selecting Data with AS Can rename (alias) a column using AS
SELECT FName AS MyName, City FROM People Example 2 Can rename (alias) a column using AS Use it to give a shorter name to a long column name Give a field a meaningful name The Aliases name is temporary, lasting only for the life of the record set Useful when a column in the table has a name that would be illegal in CF I've had to alias fields like '# of Items' June 27th- 30th 2007
23
Selecting Data with AS SELECT (LName + ‘, ’ + FName) AS MyName, City FROM People Example 3 You can concatenate two or more columns together Syntax is specific to the DBMS so refer to the DBMS documentation Can perform mathematical calculations on numeric columns SELECT Name, (Salary * 1.10) AS AdjSalary June 27th- 30th 2007
24
Selecting Data with WHERE
SELECT FName, LName, PeoCnt FROM People WHERE PeoCnt = 1 Example 4 Can select specific records with a WHERE clause Find the Person WHERE PeoCnt = 1 You can filter on columns you don’t SELECT If the datatype of the column in the WHERE clause is numeric, the value is specified without quotes June 27th- 30th 2007
25
Selecting Data with WHERE
SELECT FName, LName, City FROM People WHERE FName = 'Jack' Example 5 If the datatype of the column in the WHERE clause is alphanumeric, the value is specified with tick marks June 27th- 30th 2007
26
Selecting Data with WHERE
SELECT FName, LName, City FROM People WHERE BirthDate <= #CreateODBCDate('01/01/1901')# Example 6 The WHERE clause can contain dates Formatted dates varies by DBMS but I've found this format to be pretty universal Returns the FName, LName, and City of all people born before Jan 1, 1901 Be careful if using date time stamps because the time stamp portion of the field makes the '=' difficult to use June 27th- 30th 2007
27
Selecting Data with AND or OR
SELECT FName, LName, City FROM People WHERE BirthDate <= #CreateODBCDate('01/01/1901')# AND FName = 'Jack' SELECT FName, LName, City FROM People WHERE BirthDate <= #CreateODBCDate('01/01/1901')# OR FName = 'Jack' Example 7 Can use more than one parameter in your WHERE clauses Use the AND clause to match both parameters Use the OR clause to match one of the parameters June 27th- 30th 2007
28
Selecting Data with IN SELECT FName, LName, PeoCnt FROM People WHERE PeoCnt IN (1,3,4) Example 8 Can search for a match on multiple values using the IN clause Values are separated with commas and are enclosed with parentheses This performs the equivalent of an “OR” search WHERE PeoCnt = 1 OR PeoCnt = 3 OR PeoCnt = 4 June 27th- 30th 2007
29
Selecting Data with NOT
SELECT FName, LName, PeoCnt FROM People WHERE PeoCnt NOT IN (3,5,7) SELECT FName, LName, City FROM People WHERE BirthDate IS NOT NULL Example 9 To negate a condition, use the NOT operator June 27th- 30th 2007
30
Selecting Data with LIKE
SELECT FName, LName, City FROM People WHERE FName LIKE ‘J%’ Example 10 Can search for a match of wildcards using the LIKE clause Finds all FName records beginning with a J % can be used anywhere in the string To find records with name containing “ar”, like Charles, Arnold, Barbara, Karen, use WHERE FName LIKE ‘%ar%’ Beware: wildcard matches are generally the slowest form of filtering June 27th- 30th 2007
31
Selecting Data With AND
SELECT FName, LName, Pet_Name, TypeOfPet FROM People, Pets, PetTypes WHERE People.PeoCnt = Pets.PeoCnt AND Pets.PetTypeCnt = PetTypes.PetTypeCnt Example 11 This query will return all people that have pets and their pets names This is done using a JOIN I prefer to use the WHERE clause to make my joins unless I need to use an OUTER join to select all data from one table and only matching records from another table. (Not covered in this session) June 27th- 30th 2007
32
Ordering Selected Data
SELECT FName, LName, Pet_Name, TypeOfPet FROM People, Pets, PetTypes WHERE People.PeoCnt = Pets.PeoCnt AND Pets.PetTypeCnt = PetTypes.PetTypeCnt ORDER BY LName DESC, Pet_Name Example 12 Use ORDER BY to sort the record set Can specify multiple, comma-separated columns Data is sorted by the first column, then by the second column, etc… Data is sorted in ascending order by default Force descending order with DESC clause June 27th- 30th 2007
33
Creating Dynamic Queries
SELECT FName, LName, City FROM People WHERE PeoCnt = #Form.PeoCnt# SELECT FName, LName, City FROM People WHERE FName = '#Form.FName#' Example 13 Can search for a match based on Form variables Alphanumeric variables need tick marks, numeric variables do not June 27th- 30th 2007
34
Creating Dynamic Queries
SELECT FName, LName, City FROM People WHERE <CFLOOP FROM="1" TO="#ArrayLen(CityArray)#" INDEX="cc"> <CFIF cc EQ 1>City = '#CityArray[cc]#'<CFELSE> OR City = '#CityArray[cc]#'</CFIF></CFLOOP> Example 14 CF builds the SQL at run time using conditional statements and variables Powerful yet easy to use feature of CF CF processes the CF tags and variables before passing the resulting SQL to the database June 27th- 30th 2007
35
Creating Dynamic Queries
In this case we take all of the selected City names and place them into an Array called CityArray. <CFSET CityArray = ListToArray(Form.City)> You could just loop over the form control itself like a LIST Look at debug output (<CFDUMP> Works well) I prefer to dump the form control into an Array, developers choice IMHO June 27th- 30th 2007
36
INSERT Operations INSERT INTO People (FName, LName, Address, City, State, ZipCode) VALUES ('#Form.FName#', '#Form.LName#', '#Form.Address#', '#FORM.City#', '#Form.State#', '#Form.ZipCode#') Example 15 The INSERT statement inserts one or more rows into a table Include all columns that do not permit nulls Data can be inserted into one table at a time only INSERT can be tied to Form Controls (SELECT, INPUT, Radio, etc…) June 27th- 30th 2007
37
UPDATE Operations UPDATE People SET FName = 'Santa Rockin', LName = 'My Clause' WHERE PeoCnt = 1 Example 16 The UPDATE statement updates data in one or more rows: Specify the table to be updated, rows to be affected, and the new values Can update several columns at once If no WHERE clause is used, change is made to ALL rows in the table. Could be disastrous! Could be intentional Use caution!!! June 27th- 30th 2007
38
Quick CFC Overview Cold Fusion Components were created to assist you in code re-use. I both like and dislike them Great for all of your Select statements I don't use them with Action pages myself, I prefer to have one Action page tied to a Form page I find them difficult to use while developing because I can't see the fields in the CFC without swapping windows. Queries are stored in their own CFC template Queries get 'Called' from the template that needs them June 27th- 30th 2007
39
Quick CFC Overview Creating a CFC: <CFCOMPONENT name="DropDowns"
hint="Contains methods that expose the drop down list details."> <CFFUNCTION NAME="GetPetTypes" RETURNTYPE="query" OUTPUT="No" HINT="Return all of the Pet Types"> <CFARGUMENT NAME="MyPetType" REQUIRED="No" TYPE="string"> <CFSET var QryPetTypes = ""> <CFQUERY NAME="QryPetTypes" DATASOURCE="#Request.dsn#"> SELECT PetTypeCnt, TypeOfPet FROM PetTypes <CFIF IsDefined("MyPetType")>WHERE TypeOfPet='#MyPetType#'</CFIF> </CFQUERY> <CFRETURN QryPetTypes> </CFFUNCTION> </CFCOMPONENT> June 27th- 30th 2007
40
Quick CFC Overview Calling a CFC:
<CFINVOKE COMPONENT="DropDowns" METHOD="GetPetTypes" RETURNVARIABLE="QryPetTypes"></CFINVOKE> <CFOUTPUT QUERY="QryPetTypes"> #PetTypeCnt#, #TypeOfPet#<BR> </CFOUTPUT> This template calls DropDowns.cfc because that is where the QryPetTypes query is residing June 27th- 30th 2007
41
Conclusion Database and SQL processing is easy
CF makes it even easier Still plenty more for you to learn, I.E. BLOCKFACTOR CACHEDWITHIN <CFQUERYPARAM> Practice the examples offered here Download the sample application June 27th- 30th 2007
42
Q&A ? June 27th- 30th 2007
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.