Difference between revisions of "DD Class6"

esse quam videri
Jump to: navigation, search
(Normalization)
m (Text replacement - "syntaxhighlight lang="csharp" line="1" " to "syntaxhighlight lang="csharp"")
 
(36 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[Category:Data Design]]
+
==Binding to SQL or XML==
  
  
==Primary Keys==
+
http://iam.colum.edu/dd/classsource/class3/RadioBindDropDownStates.aspx
The candidate key selected as being most important for identifying a body of information (an entity, object or record).
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/RadioBindDropDownStates.aspx source]
  
==Normalization==
+
http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStates2.aspx
Definition from foldoc
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/DataBindDropDownStates2.aspx source]
  
'''First Normal'''
+
Notice the Name and the Value in both of these examples are the same. ListControls support both Name and Value fields and these can have different values. Be when a single dimensional data source is bound to the control the name and value will be the same.
:Form eliminates repeating groups by putting each into a separate table and connecting them with a one-to-many relationship.
+
In order to define these parameter we need to have a named field from an object.
Not Following First Normal Form
+
btw it just wouldn't be fair if I didn't show you how to do it with objects
  
 +
http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesObjective.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/DataBindDropDownStatesObjective.aspx source]
  
Blog1
+
and finally databinding to sql server (really we are using and object here DataTable)
{| class="wikitable" cellpadding="5" cellspacing="0"
+
 
!BlogID !! BlogText !! recCreationDate !! Mood
+
http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesData.aspx
|-
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/DataBindDropDownStatesData.aspx source]
|1 || Blog1 || 03/30/03 || Happy
+
 
|-
+
 
|2 || Blog2 || 03/30/03 || Happy
+
Same example with XML
|-
+
 
|3 || Blog3 || 03/30/03 || Sad
+
http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesCountryData.aspx
|-
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/DataBindDropDownStatesCountryData.aspx source]
|4 || Blog4 || 03/30/03 || Happy
+
 
|-
+
==SQL server==
|5 || Blog4 || 03/30/03 || Mad
+
 
|}
+
The sql language contains commands for everything that the sql server can do.
 +
 
 +
Create Table
 +
:demo in SQLStudio and VS
 +
 
 +
Create Table Syntax
 +
<sql>
 +
CREATE TABLE table_name
 +
(
 +
  column_name datatype[(length)] [NULL | NOT NULL]
 +
)
 +
#Example
 +
CREATE TABLE temp_user (
 +
userID int PRIMARY KEY IDENTITY NOT NULL ,
 +
firstName varchar (250) NOT NULL ,
 +
lastName varchar (250) NOT NULL
 +
)
 +
#MSSQL Example
 +
CREATE TABLE [dbo].[user] (
 +
[userID] [int] IDENTITY (1, 1) NOT NULL ,
 +
[firstName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 +
[lastName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
 +
) ON [PRIMARY]
 +
GO
 +
</sql>
 +
 
 +
  The 'GO' keyword is special in T-SQL it executes the current batch of statements
 +
 
 +
Alter Table
 +
<sql>
 +
ALTER TABLE temp_user
 +
add recCreationDate datetime NULL
 +
#You cannot add a column that is NOT NULL without specifying a default value
 +
GO
 +
</sql>
 +
 
 +
 
 +
Code to create the States Table from the above Example
 +
 
 +
http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/states.sql
 +
 
 +
http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/statesSimple.sql
 +
 
 +
<sql>
 +
CREATE TABLE states
 +
(
 +
id int NOT NULL IDENTITY (1, 1),
 +
StateName varchar(50) NOT NULL,
 +
StateAbr nchar(3) NOT NULL
 +
)  ON [PRIMARY]
 +
GO
 +
ALTER TABLE states ADD CONSTRAINT
 +
PK_states PRIMARY KEY CLUSTERED
 +
(
 +
id
 +
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 +
 
 +
</sql>
 +
 
 +
 
 +
More SQL Syntax we'll study this in the comming weeks
 +
[[SQL SelectInsertUpdateDeleteSyntax]]
 +
 
 +
Query Analyzer
 +
:SQL Query Analyzer is an interactive, graphical tool that enables a database
 +
administrator or developer to write queries, execute multiple queries simultaneously,
 +
view results, analyze the query plan, and receive assistance to improve the query performance. -MSSQL help
 +
 
 +
Sql code to insert all the states in the states table
 +
 
 +
http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/InsertStates.sql
 +
 
 +
<sql>
 +
INSERT into states (StateName, StateAbr) values ('Non US Province' , '')
 +
INSERT into states (StateName, StateAbr) values ('Alabama' , 'AL')
 +
INSERT into states (StateName, StateAbr) values ('Alaska' , 'AK')
 +
INSERT into states (StateName, StateAbr) values ('Arizona' , 'AZ')
 +
INSERT into states (StateName, StateAbr) values ('Arkansas' , 'AR')
 +
INSERT into states (StateName, StateAbr) values ('Armed Forces Americas' , 'AA')
 +
...
 +
</sql>
 +
 
 +
==SQL Syntax==
 +
 
 +
Create Table
 +
 
 +
<sql>
 +
CREATE TABLE table_name
 +
{
 +
coulumn_name datatype[(length)] [NULL | NOT NULL}
 +
}
 +
#Example
 +
CREATE TABLE temp_user (
 +
userID int PRIMARY KEY IDENTITY NOT NULL ,
 +
firstName varchar (250) NOT NULL ,
 +
lastName varchar (250) NOT NULL
 +
)
 +
#MSSQL Example
 +
CREATE TABLE [dbo].[user] (
 +
[userID] [int] IDENTITY (1, 1) NOT NULL ,
 +
[firstName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
 +
[lastName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
 +
) ON [PRIMARY]
 +
GO
 +
</sql>
 +
 
 +
<sql>
 +
Alter Table
 +
 
 +
ALTER TABLE temp_user
 +
add recCreationDate datetime NULL
 +
#You cannot add a column that is NOT NULL wihout specifing a default value
 +
GO
 +
</sql>
 +
 
 +
SQL Syntax
 +
 
 +
===Single Table Operations===
 +
If you are dealing with more than one table then all of your sql statement must be wrapped in a transaction. A transaction it group of statements that  will succeed or fail as a whole. All the statements must succeed if one fails then the entire transaction is rolled back.
 +
 
 +
SQL statements
 +
 
 +
*INSERT
 +
*UPDATE
 +
*SELECT
 +
*DELETE
 +
 
 +
'''INSERT'''
 +
<sql>
 +
      INSERT into temp_user
 +
      ( firstName, lastName, recCreationDate )
 +
      VALUES
 +
      ('jeff', 'meyers', '3/24/03')
 +
     
 +
</sql>
 +
 
 +
[[More Inserts for temp_user]]
 +
 
 +
'''SELECT'''
 +
<sql>
 +
      /* Select everyting from the temp_user table */
 +
      SELECT * from temp_user 
 +
     
 +
      /* Select userID,firtName,lastName from the temp_user table */
 +
      SELECT userID,firstName,lastName from temp_user
 +
     
 +
      /* Select userID,firtName,lastName from the temp_user table
 +
      where firstName is jeff*/
 +
      SELECT userID,firtName,lastName from temp_user where firstName = 'jeff'
 +
     
 +
      /* Select userID,firtName,lastName from the temp_user table
 +
      where firstName is jeff then sorts by lastName*/
 +
      SELECT userID,firstName,lastName from temp_user where firstName = 'jeff'
 +
      order by LastName
 +
     
 +
      /* Select userID,firtName,lastName from the temp_user table
 +
      where firstName is jeff then sorts by lastName in reverse order*/
 +
      SELECT userID,firstName,lastName from temp_user where firstName = 'jeff'
 +
      order by LastName DESC
 +
     
 +
      /* Select userID,firtName,lastName from the temp_user table
 +
      where firstName is jeff and last name is meyers then sorts by lastName
 +
      in reverse order*/
 +
      SELECT userID,firstName,lastName from temp_user where firstName = 'jeff'
 +
      and lastName = 'meyers'
 +
      order by LastName DESC
 +
</sql>
 +
 +
'''UPDATE'''
 +
<sql>
 +
      UPDATE temp_user set firstName = 'jeffrey' where firstName = 'jeff'
 +
     
 +
</sql>
 +
 
 +
'''DELETE'''
 +
<sql>
 +
      DELETE from temp_user where firstName = 'jeffrey'
 +
     
 +
</sql>
 +
Query Analyzer
 +
 
 +
SQL Query Analyzer is an interactive, graphical tool that enables a database administrator or developer to write queries, execute multiple queries simultaneously, view results, analyze the query plan, and receive assistance to improve the query performance. -MSSQL help
 +
Stored Procedures
  
Tables that Follow First normal form
+
A stored procedure is a collection of compiled Transact-SQL statements that can take and return user-supplied parameters. Views
  
Blog2
+
A view is simply a SELECT query saved in the database. Thus, most operations you can perform on queries you can also perform on views. However, there are some operations that apply only to one or the other. -MSSQL Help
{| class="wikitable" cellpadding="5" cellspacing="0"
 
! BlogID !! BlogText !! recCreationDate !! MoodID
 
|-
 
|1 || Blog1 || 03/30/03 || 1
 
|-
 
|2 || Blog2 || 03/30/03 || 1
 
|-
 
|3 || Blog3 || 03/30/03 || 2
 
|-
 
|4 || Blog4 || 03/30/03 || 1
 
|-
 
|5 || Blog4 || 03/30/03 || 3
 
|}
 
Mood
 
{| class="wikitable" cellpadding="5" cellspacing="0"
 
!MoodID !! MoodName
 
|-
 
|1 || Happy
 
|-
 
|2 || Sad
 
|-
 
|3 || Mad
 
|-
 
|4 || Afraid
 
|}
 
  
===Second Normal Form===
 
  
Second Normal Form eliminates functional dependencies on a partial key by putting the fields in a separate table from those that are dependent on the whole key. Must be in first normal form.
+
==DataProviders==
Not Normal
+
[http://msdn2.microsoft.com/en-us/library/a6cd7c08(VS.80).aspx .NET Framework Data Providers Data Providers] (language from OLE DB)
{| class="wikitable" cellpadding="5" cellspacing="0"
 
! CustNum !! FirstName !! LastName !! Address !! City !! State !! ZIP
 
|-
 
| 1 || John || Doe || 12 Main Street || Sea Cliff || NY || 11579
 
|-
 
| 2 || Alan || Johnson || 82 Evergreen Tr || Sea Cliff || NY || 11579
 
|-
 
| 3 || Beth || Thompson || 1912 NE 1st St  || Miami || FL  || 33157
 
|-
 
| 4 || Jacob  || Smith || 142 Irish Way || South Bend || IN || 46637
 
|-
 
| 5 || Sue || Ryan || 412 NE 1st St || Miami || FL  || 33157
 
|}
 
  
 +
# System.Data.SqlClient
 +
# System.Data.OleDb
 +
# System.Data.Odbc
 +
# System.Data.OracleClient
  
Normal
+
Abstract Factory the allows the Abstract Factory the allows the DataProviders to the changed at run time.</p>
{| class="wikitable" cellpadding="5" cellspacing="0"
+
Abstract Factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes
! ZIP !! City !! State
 
|-
 
| 11579 || Sea Cliff || NY
 
|-
 
|33157  || Miami || FL
 
|-
 
|46637 || South Bend || IN
 
|}
 
  
 +
http://www.dofactory.com/Patterns/PatternAbstract.aspx
 +
       
 +
[http://msdn2.microsoft.com/en-us/library/system.data.common.dbproviderfactory.aspx DbProviderFactory]
  
{| class="wikitable" cellpadding="5" cellspacing="0"
+
MySQL Connector
! CustNum !! FirstName !! LastName !! Address !! ZIP
+
http://dev.mysql.com/downloads/connector/net/5.0.html
|-
 
|1 || John || Doe || 12 Main Street || 11579
 
|-
 
|2 || Alan || Johnson || 82 Evergreen Tr || 11579
 
|-
 
|3 || Beth || Thompson || 1912 NE 1st St || 33157
 
|-
 
|4 || Jacob || Smith || 142 Irish Way || 46637
 
|-
 
|5 || Sue || Ryan || 412 NE 1st St || 33157
 
|}
 
  
===Third Normal Form===
+
==Data Consumers==
  
Third Normal Form eliminates functional dependencies on non-key fields by putting them in a separate table. At this stage, all non-key fields are dependent on the key, the whole key and nothing but the key. Must be in second normal form.
+
*Data Adapter
 +
*DataReader http://iam.colum.edu/dd/classsource/ado/dataReader.aspx [http://iam.colum.edu/dd/gbrowser.php?file=/classsource/ado/dataReader.aspx source]
  
Not normal
 
{| class="wikitable" cellpadding="5" cellspacing="0"
 
!Company !! City !! State !! ZIP
 
|-
 
| Acme Widgets || New York || NY || 10169
 
|-
 
| ABC Corporation || Miami || FL  || 33196
 
|-
 
| XYZ, Inc. || Columbia || MD || 21046
 
|}
 
  
Normal
 
  
{| class="wikitable" cellpadding="5" cellspacing="0"
+
1 Connection Object
! KompanyID !! KompanyName !! Zip
+
<syntaxhighlight lang="csharp">
|-
+
//Connection string comes from web config
|1 || Acme Widgets || 10169
+
SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ConnectionString);           
|-
+
</syntaxhighlight>
|2 || ABC Corporation || 33196
 
|-
 
|3  || XYZ, Inc. || 21046
 
|}
 
  
 +
web.config connection strings
  
{| class="wikitable" cellpadding="5" cellspacing="0"
+
<xml>
! Zip !! CityID
+
<configuration>
|-
+
|10169 || 1
+
              <connectionStrings>
|-
+
|33196 || 2
+
  <add name="cheeseConnectionString" connectionString="Data Source=iamdb;Initial Catalog=cheese;User ID=student;Password=Student" providerName="System.Data.SqlClient"/>
|-
+
      </connectionStrings>
|21046 || 3
+
</xml>
|}
 
  
 +
2 Command Object
 +
<syntaxhighlight lang="csharp">string strSQL = "SELECT CheeseName,CheeseDescription FROM cheese";
 +
   
 +
    string strResultsHolder = "";
 +
   
 +
    SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
 +
</syntaxhighlight>
  
{| class="wikitable" cellpadding="5" cellspacing="0"
+
3 Reader and Reading
! CityID !! City
+
<syntaxhighlight lang="csharp">
|-
+
SqlDataReader objDataReader = null;                            //Reader to read through the result
| 1 || New York
+
    try
|-
+
    {
| 2 || Miami
+
        objConnection.Open();                                      //Open Connection
|-
+
        objDataReader = objCommand.ExecuteReader();
| 3  || Columbia
 
|}
 
  
 +
        while (objDataReader.Read() == true)
 +
        {
 +
            strResultsHolder += String.Format("<b>{0}</b>:{1}<br /><br />",
 +
                objDataReader["CheeseName"], objDataReader["CheeseDescription"]);
 +
        }
 +
    }
 +
    catch (Exception e)
 +
    {
 +
        lblErr.Text = "Connection failed to open successfully.<br/>";
 +
        lblErr.Text += e.ToString();
 +
    }
 +
    finally
 +
    {
 +
        objDataReader.Close();      //Close Reader
 +
        objConnection.Close();      //Close Connection
  
{| class="wikitable" cellpadding="5" cellspacing="0"
+
    }
! StateID !! State
+
    //Write results
|-
+
    divListCheese.InnerHtml = strResultsHolder;
| 1 || NY
+
}
|-
 
| 2 || FL
 
|-
 
| 3 || MD
 
|}
 
  
===Fourth Normal Form===
+
</syntaxhighlight>
Fourth Normal Form
 
:separates independent multi-valued facts stored in one table into separate tables.
 
  
===Fifth Normal Form===  
+
==ADO.NET Objects==
Fifth Normal Form
 
:breaks out data redundancy that is not covered by any of the previous normal forms.
 
  
http://home.earthlink.net/~billkent/Doc/simple5.htm.
+
ADO.NET Objects
 +
[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconadonetarchitecture.asp ADO.NET Architecture]
  
==Relationships==
+
{{Template:ADO.NET Diagram}}
  
'''one-to-many'''
+
[[Template:ADO.NET Diagram]]
  
Single primary key has many foreign keys. A person many have many email addresses.
+
== Data Reader==
  
'''one-to-one'''
+
DataReader
 +
:The ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. It buffers the data :rather than trying to return all the data at once whick increases efficiency. [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcontheadonetdatareader.asp MS DataReader]
  
A Single primary key may only have on foreign key. A sweater can only be one color.
+
http://iam.colum.edu/dd/classsource/class4/datareader.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/datareader.aspx source]
  
'''many-to-many'''
+
==ASPX and execute Non-query==
  
A junction table is used to normalize data. A student may take many courses and a course may have many students.
+
ExecuteNonQuery
 +
:You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or :creating database objects such as tables), or to change the data in a database without using a DataSet by executing :UPDATE, INSERT, or DELETE statements. Although the ExecuteNonQuery does not return any rows, any output parameters :or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the :return value is the number of rows affected by the command. For all other types of statements, the return value is :-1. If a rollback occurs, the return value is also -1.
 +
[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqlcommandclassexecutenonquerytopic.asp ExecuteNonQuery() topic on msdn]
  
The relationship is created in the diagram too by dragging on primary key to the foreign key.
+
show examples of the old execute non query
  
==Views==
+
<syntaxhighlight lang="csharp">
 +
    //Connection string comes from web config
 +
    SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ConnectionString);
 +
   
 +
    // Create and open the connection object
 +
    SqlConnection objConnection = new SqlConnection(strConnection);
 +
    objConnection.Open();    //open the connection
 +
   
 +
    // set the SQL string
 +
    string strSQL = "INSERT INTO temp_user (FirstName , LastName ) VALUES ( 'Beth' , 'Hart' )";
 +
   
 +
    // Create the Command and set its properties
 +
    SqlCommand objCmd = new SqlCommand(strSQL, objConnection);
 +
   
 +
    // execute the command
 +
    int i = objCmd.ExecuteNonQuery();
 +
    objConnection.Close();    //close the conection
 +
</syntaxhighlight>
  
UserTest
+
INSERT
{| class="wikitable" cellpadding="5" cellspacing="0"
 
! UserID !! UserName !! LastLogon
 
|-
 
| 1 || jmeyers 3/30/03
 
|2 || bgates 4/1/03
 
|3 || sjobs 4/2/03
 
|4 || ltorvalds 4/3/03
 
|}
 
  
 +
http://iam.colum.edu/dd/classsource/class4/directsqlINSERT.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/directsqlINSERT.aspx source]
  
EmailTest
+
http://iam.colum.edu/dd/classsource/class4/temp_userInsert.aspx
{| class="wikitable" cellpadding="5" cellspacing="0"
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/temp_userInsert.aspx source]
! EmailID !! UserID !! EmailAddress !! Active !! displayEmail
 
|-
 
| 1 || 1 || jeff@interactive.colum.edu || 1 || 0
 
|-
 
| 2 || 1 || only_a_test@hotmail.com || 0 || 0
 
|-
 
| 3 || 2 || bgates@microsoft.com || 1 || 0
 
|}
 
  
[INNER] JOIN
+
UPDATE
  
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in User that do not have matches in Email, those rows will not be listed.
+
http://iam.colum.edu/dd/classsource/class4/directsqlUPDATEHartless.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/directsqlUPDATEHartless.aspx source]
  
-- ANSI Style
+
DELETE
SELECT u.UserID,
 
u.UserName,
 
u.LastLogon,
 
e.EmailAddress,
 
e.active,
 
e.displayEmail
 
FROM UserTest u
 
JOIN EmailTest e ON e.UserID = u.UserID
 
  
--Theta style
+
http://iam.colum.edu/dd/classsource/class4/directsqlDELETE.aspx
<sql>
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/directsqlDELETE.aspx source]
SELECT u.UserID,
 
u.UserName,
 
u.LastLogon,
 
e.EmailAddress,
 
e.active,
 
e.displayEmail
 
FROM UserTest u,
 
EmailTest e
 
WHERE e.UserID = u.UserID
 
</sql>
 
  
results
+
http://iam.colum.edu/dd/classsource/class4/temp_userDelete.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/temp_userDelete.aspx source]
  
<pre>
+
Example with panels and a form
UserID      UserName            LastLogon                    EmailAddress                    active displayEmail
 
----------- ------------------- ----------------------------- -------------------------------- ------ ------------
 
1          jmeyers            2003-03-30 00:00:00.000      jeff@interactive.colum.edu      1      0
 
1          jmeyers            2003-03-30 00:00:00.000      only_a_test@hotmail.com          0      0
 
2          bgates              2003-04-01 00:00:00.000      bgates@microsoft.com            1      0
 
  
(3 row(s) affected)
+
http://iam.colum.edu/dd/classsource/class4/temp_userInsert.aspx
</pre>
+
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/temp_userInsert.aspx source]
  
LEFT [OUTER] JOIN
 
  
The LEFT JOIN returns all the rows from the first table (User), even if there are no matches in the second table (Email). If there are rows in User that do not have matches in Email, those rows also will be listed.
+
http://iam.colum.edu/dd/classsource/class4/temp_userDelete.aspx
 +
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class4/temp_userDelete.aspx source]
  
<sql>
+
==Homework==
SELECT u.UserID,
 
u.UserName,
 
u.LastLogon,
 
e.EmailAddress,
 
e.active,
 
e.displayEmail
 
FROM UserTest u
 
LEFT JOIN EmailTest e ON e.UserID = u.UserID
 
</sql>
 
  
<pre>
 
UserID      UserName    LastLogon                EmailAddress                active displayEmail
 
----------- ------------ ------------------------- ---------------------------- ------ ------------
 
1          jmeyers      2003-03-30 00:00:00.000  jeff@interactive.colum.edu  1      0
 
1          jmeyers      2003-03-30 00:00:00.000  only_a_test@hotmail.com      0      0
 
2          bgates      2003-04-01 00:00:00.000  bgates@microsoft.com        1      0
 
3          sjobs        2003-04-02 00:00:00.000  NULL                        NULL  NULL
 
4          ltorvalds    2003-04-03 00:00:00.000  NULL                        NULL  NULL
 
  
(5 row(s) affected)
+
1. Create a Cheese Table in you database
</pre>
 
  
RIGHT [OUTER] JOIN
+
Cheese
 +
{| class="wikitable" cellpadding="5" cellspacing="0"
 +
!CheeseID !!  CheeseName !! CheeseDescription
 +
|-
 +
|1 || SomeCheese ||  SomeCheese Desc
 +
|-
 +
|2 || AnotherCheese || AnotherCheese Desc
 +
|}
  
The RIGHT JOIN returns all the rows from the second table (Email), even if there are no matches in the first table (User). If there had been any rows in Email that did not have matches in User, those rows also would have been listed.
+
#Create a page the reads all the data in you cheese table using a DataReader and displays it in an aspx page
 +
#Create a page that adds cheese to the cheese table using ExecuteNonQuery and an aspx form
  
<sql>
+
2. Create a states table in you database as shown above. Add all the states to the table sql is above. Now Redo you cheese form assignment but pull the state Names and Abbreviations from you database. The state names should be bound to a DropDown List as the DataTextField and the state abbreviation should be the DataValueField.
SELECT u.UserID,
 
u.UserName,
 
u.LastLogon,
 
e.EmailAddress,
 
e.active,
 
e.displayEmail
 
FROM UserTest u
 
RIGHT JOIN EmailTest e ON e.UserID = u.UserID
 
</sql>
 
  
results
+
3. Create a regions and consistency table in you database. Add the appropriate fields to each table. Then replace the static check-box list of consistencies and radiobuttonlist of regions (you don't need to completely populate the regions table but you should add all the consistencies from the form).
  
<pre>
+
UserID      UserName            LastLogon                    EmailAddress                    active displayEmail
 
----------- ------------------- ----------------------------- -------------------------------- ------ ------------
 
1          jmeyers            2003-03-30 00:00:00.000      jeff@interactive.colum.edu      1      0
 
1          jmeyers            2003-03-30 00:00:00.000      only_a_test@hotmail.com          0      0
 
2          bgates              2003-04-01 00:00:00.000      bgates@microsoft.com            1      0
 
  
(3 row(s) affected)
+
Read Chapter 5 in BAD
</pre>
 
Making views in enterprise manager is easy. Just add the tables you want to join and click. It does all the typing for you.
 

Latest revision as of 03:23, 9 February 2016

Binding to SQL or XML

http://iam.colum.edu/dd/classsource/class3/RadioBindDropDownStates.aspx source

http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStates2.aspx source

Notice the Name and the Value in both of these examples are the same. ListControls support both Name and Value fields and these can have different values. Be when a single dimensional data source is bound to the control the name and value will be the same. In order to define these parameter we need to have a named field from an object. btw it just wouldn't be fair if I didn't show you how to do it with objects

http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesObjective.aspx source

and finally databinding to sql server (really we are using and object here DataTable)

http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesData.aspx source


Same example with XML

http://iam.colum.edu/dd/classsource/class3/DataBindDropDownStatesCountryData.aspx source

SQL server

The sql language contains commands for everything that the sql server can do.

Create Table

demo in SQLStudio and VS

Create Table Syntax <sql> CREATE TABLE table_name (

column_name datatype[(length)] [NULL | NOT NULL]

)

  1. Example

CREATE TABLE temp_user ( userID int PRIMARY KEY IDENTITY NOT NULL , firstName varchar (250) NOT NULL , lastName varchar (250) NOT NULL )

  1. MSSQL Example

CREATE TABLE [dbo].[user] ( [userID] [int] IDENTITY (1, 1) NOT NULL , [firstName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [lastName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] GO </sql>

The 'GO' keyword is special in T-SQL it executes the current batch of statements

Alter Table <sql> ALTER TABLE temp_user add recCreationDate datetime NULL

  1. You cannot add a column that is NOT NULL without specifying a default value

GO </sql>


Code to create the States Table from the above Example

http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/states.sql

http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/statesSimple.sql

<sql> CREATE TABLE states ( id int NOT NULL IDENTITY (1, 1), StateName varchar(50) NOT NULL, StateAbr nchar(3) NOT NULL ) ON [PRIMARY] GO ALTER TABLE states ADD CONSTRAINT PK_states PRIMARY KEY CLUSTERED ( id ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

</sql>


More SQL Syntax we'll study this in the comming weeks SQL SelectInsertUpdateDeleteSyntax

Query Analyzer

SQL Query Analyzer is an interactive, graphical tool that enables a database

administrator or developer to write queries, execute multiple queries simultaneously, view results, analyze the query plan, and receive assistance to improve the query performance. -MSSQL help

Sql code to insert all the states in the states table

http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class3/states/InsertStates.sql

<sql> INSERT into states (StateName, StateAbr) values ('Non US Province' , ) INSERT into states (StateName, StateAbr) values ('Alabama' , 'AL') INSERT into states (StateName, StateAbr) values ('Alaska' , 'AK') INSERT into states (StateName, StateAbr) values ('Arizona' , 'AZ') INSERT into states (StateName, StateAbr) values ('Arkansas' , 'AR') INSERT into states (StateName, StateAbr) values ('Armed Forces Americas' , 'AA') ... </sql>

SQL Syntax

Create Table

<sql> CREATE TABLE table_name {

coulumn_name datatype[(length)] [NULL | NOT NULL}

}

  1. Example

CREATE TABLE temp_user ( userID int PRIMARY KEY IDENTITY NOT NULL , firstName varchar (250) NOT NULL , lastName varchar (250) NOT NULL )

  1. MSSQL Example

CREATE TABLE [dbo].[user] ( [userID] [int] IDENTITY (1, 1) NOT NULL , [firstName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [lastName] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] GO </sql>

<sql> Alter Table

ALTER TABLE temp_user add recCreationDate datetime NULL

  1. You cannot add a column that is NOT NULL wihout specifing a default value

GO </sql>

SQL Syntax

Single Table Operations

If you are dealing with more than one table then all of your sql statement must be wrapped in a transaction. A transaction it group of statements that will succeed or fail as a whole. All the statements must succeed if one fails then the entire transaction is rolled back.

SQL statements

  • INSERT
  • UPDATE
  • SELECT
  • DELETE

INSERT <sql>

     		 INSERT into temp_user 
     		 ( firstName, lastName, recCreationDate )
     		 VALUES
     		 ('jeff', 'meyers', '3/24/03')
     		 

</sql>

More Inserts for temp_user

SELECT <sql>

     		 /* Select everyting from the temp_user table */
     		 SELECT * from temp_user  
     		 
     		 /* Select userID,firtName,lastName from the temp_user table */
     		 SELECT userID,firstName,lastName from temp_user
     		 
     		 /* Select userID,firtName,lastName from the temp_user table 
     		 	where firstName is jeff*/
     		 SELECT userID,firtName,lastName from temp_user where firstName = 'jeff'
     		 
     		 /* Select userID,firtName,lastName from the temp_user table 
     		 	where firstName is jeff then sorts by lastName*/
     		 SELECT userID,firstName,lastName from temp_user where firstName = 'jeff' 
     		 order by LastName
     		 
     		 /* Select userID,firtName,lastName from the temp_user table 
     		 	where firstName is jeff then sorts by lastName in reverse order*/
     		 SELECT userID,firstName,lastName from temp_user where firstName = 'jeff' 
     		 order by LastName DESC
     		 
     		 /* Select userID,firtName,lastName from the temp_user table 
     		 	where firstName is jeff and last name is meyers then sorts by lastName 
     			in reverse order*/
     		 SELECT userID,firstName,lastName from temp_user where firstName = 'jeff' 
     		 and lastName = 'meyers'
     		 order by LastName DESC

</sql>

UPDATE <sql>

     		 UPDATE temp_user set firstName = 'jeffrey' where firstName = 'jeff'
     		 

</sql>

DELETE <sql>

     		 DELETE from temp_user where firstName = 'jeffrey'
     		 

</sql> Query Analyzer

SQL Query Analyzer is an interactive, graphical tool that enables a database administrator or developer to write queries, execute multiple queries simultaneously, view results, analyze the query plan, and receive assistance to improve the query performance. -MSSQL help Stored Procedures

A stored procedure is a collection of compiled Transact-SQL statements that can take and return user-supplied parameters. Views

A view is simply a SELECT query saved in the database. Thus, most operations you can perform on queries you can also perform on views. However, there are some operations that apply only to one or the other. -MSSQL Help


DataProviders

.NET Framework Data Providers Data Providers (language from OLE DB)

  1. System.Data.SqlClient
  2. System.Data.OleDb
  3. System.Data.Odbc
  4. System.Data.OracleClient

Abstract Factory the allows the Abstract Factory the allows the DataProviders to the changed at run time.</p> Abstract Factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes

http://www.dofactory.com/Patterns/PatternAbstract.aspx

DbProviderFactory

MySQL Connector http://dev.mysql.com/downloads/connector/net/5.0.html

Data Consumers


1 Connection Object

//Connection string comes from web config
SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ConnectionString);

web.config connection strings

<xml> <configuration>

              <connectionStrings>

<add name="cheeseConnectionString" connectionString="Data Source=iamdb;Initial Catalog=cheese;User ID=student;Password=Student" providerName="System.Data.SqlClient"/> </connectionStrings> </xml>

2 Command Object

string strSQL = "SELECT CheeseName,CheeseDescription FROM cheese";
    
    string strResultsHolder = "";
    
    SqlCommand objCommand = new SqlCommand(strSQL, objConnection);

3 Reader and Reading

SqlDataReader objDataReader = null;                             //Reader to read through the result
    try
    {
        objConnection.Open();                                       //Open Connection
        objDataReader = objCommand.ExecuteReader();

        while (objDataReader.Read() == true)
        {
            strResultsHolder += String.Format("<b>{0}</b>:{1}<br /><br />",
                objDataReader["CheeseName"], objDataReader["CheeseDescription"]);
        }
    }
    catch (Exception e)
    {
        lblErr.Text = "Connection failed to open successfully.<br/>";
        lblErr.Text += e.ToString();
    }
    finally
    {
        objDataReader.Close();      //Close Reader
        objConnection.Close();      //Close Connection

    }
    //Write results
    divListCheese.InnerHtml = strResultsHolder;
}

ADO.NET Objects

ADO.NET Objects ADO.NET Architecture

  • Connection - used to connect the data consumer ASP.NEt to a Data Provider
  • Command - used to issue SQL commands to a Data Provider
  • DataReader - A fast forward only DataSet that holds one or more resultsets.Fast and efficient
  • DataSet - can contain multiple tables and relationships between tables
  • DataAdapter - Passes Data from a Connection object to a DataSet and updates that data. ( A bridge used to fill dataSets with DataAdapter.Fill and DataAdapter.Update)
  • DataTable - structure that holds a set of rows and columns
  • DataRelation - holds relations between DataTables in a DataSet
  • DataRow - data within data row
  • DataView - a specific view of the DataTables within a Dataset

Connection
DataAdapter
DataReader
DataSet
DataTable
DataView
DataRow
DataRow
DataRow
DataTable
DataRow
DataRow
DataRow
DataTable
DataRow
DataRow
DataRow

Template:ADO.NET Diagram

Data Reader

DataReader

The ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. It buffers the data :rather than trying to return all the data at once whick increases efficiency. MS DataReader

http://iam.colum.edu/dd/classsource/class4/datareader.aspx source

ASPX and execute Non-query

ExecuteNonQuery

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or :creating database objects such as tables), or to change the data in a database without using a DataSet by executing :UPDATE, INSERT, or DELETE statements. Although the ExecuteNonQuery does not return any rows, any output parameters :or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the :return value is the number of rows affected by the command. For all other types of statements, the return value is :-1. If a rollback occurs, the return value is also -1.

ExecuteNonQuery() topic on msdn

show examples of the old execute non query

    //Connection string comes from web config
    SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ConnectionString);
     
    // Create and open the connection object
    SqlConnection objConnection = new SqlConnection(strConnection);
    objConnection.Open();     //open the connection
    
    // set the SQL string
    string strSQL = "INSERT INTO temp_user (FirstName , LastName ) VALUES ( 'Beth' , 'Hart' )";
    
    // Create the Command and set its properties
    SqlCommand objCmd = new SqlCommand(strSQL, objConnection);
    
    // execute the command
    int i = objCmd.ExecuteNonQuery();
    objConnection.Close();    //close the conection

INSERT

http://iam.colum.edu/dd/classsource/class4/directsqlINSERT.aspx source

http://iam.colum.edu/dd/classsource/class4/temp_userInsert.aspx source

UPDATE

http://iam.colum.edu/dd/classsource/class4/directsqlUPDATEHartless.aspx source

DELETE

http://iam.colum.edu/dd/classsource/class4/directsqlDELETE.aspx source

http://iam.colum.edu/dd/classsource/class4/temp_userDelete.aspx source

Example with panels and a form

http://iam.colum.edu/dd/classsource/class4/temp_userInsert.aspx source


http://iam.colum.edu/dd/classsource/class4/temp_userDelete.aspx source

Homework

1. Create a Cheese Table in you database

Cheese

CheeseID CheeseName CheeseDescription
1 SomeCheese SomeCheese Desc
2 AnotherCheese AnotherCheese Desc
  1. Create a page the reads all the data in you cheese table using a DataReader and displays it in an aspx page
  2. Create a page that adds cheese to the cheese table using ExecuteNonQuery and an aspx form

2. Create a states table in you database as shown above. Add all the states to the table sql is above. Now Redo you cheese form assignment but pull the state Names and Abbreviations from you database. The state names should be bound to a DropDown List as the DataTextField and the state abbreviation should be the DataValueField.

3. Create a regions and consistency table in you database. Add the appropriate fields to each table. Then replace the static check-box list of consistencies and radiobuttonlist of regions (you don't need to completely populate the regions table but you should add all the consistencies from the form).


Read Chapter 5 in BAD