Databases
Topics
• Introduction to Database Management System
• Tables, Rows, and Columns
• Creating a Database in Visual Studio
• The DataGridView Control
• Connecting to an Existing Database and Using
Details View Controls
• More About Data-Bound Controls
• Selecting Data with the SQL Select Statement
Introduction to Database Management
System
A database management system (DBMS) is software
that manages large collections of data
• It is designed to store, retrieve, and manipulate data
• A C# application can interact with a DBMS through a 3-layer
manipulation
• Application: interacts with the user and sends instructions to
DBMS
• DBMS: works directly with the data and sends the result back to the
application
• Data: the data stored in DBMS
Application
DBMS
Data
Tables, Rows, and Columns
Data stored in a database are organized into tables,
rows, and columns
Each table holds a collection of related data
• A table is a two-dimensional container made of rows and
columns
• A row is a complete set of information about a single item
• A column holds an individual piece of information about the
item
Name Phone
Katie Allen 555-1234
Jill Ammons 555-5678
Each row contains data about one person Kevin Brown 555-9012
Elisa Garcia 555-3456
Jeff Jenkins 555-7890
Column Data Types
When you create a database table, you must specify a
data type for the column
• Acceptable data types are defined by DBMS, not C#
• The textbook uses Microsoft SQL Server
SQL Server Description Corresponding C# or .NET
Data Type Framework Data Type
bit True/false values bool
datetime A date and a time DateTime
decimal(t, d) A decimal value with t total digits and d digits appearing after the decimal decimal
point.
float Real numbers double
int An integer number int
money Values that represent currency decimal
nchar(n) A fixed-length Unicode string with a maximum length of n characters. string
nvarchar(n) A variable-length Unicode string with a maximum length of n characters. string
Primary Keys
Most database tables have a primary key
• A primary key is a column that can be used to identify a specific
row
• The column that is designated as the primary key must hold a
unique value for each row. For example,
• Employee ID, social security number, invoice number, sales order
number
• Sometimes the data that you want to store in a table does not
contain any unique items that can be used as a primary key
• You need to create an identity column specifically to serve as the
primary key. This column is known as an identify column.
• Identify columns typically contain integers
• Each time a new row is added to the table, the DBMS automatically
assigns a unique value to the identify column
Creating a Database in Visual Studio
A .NET application uses several
components, arranged in layers, to
connect to a database
• Data Source – a source of data with which the
application can work
• Table Adapter – connects to a data source and Application
retrieves data from a table in a data source Binding Source
• Dataset – gets a copy of a table from the table Dataset
adapter and keeps the copy of the table in Table Adapter
memory Data Source
• Binding Source – a component that can
connect user interface controls directly to a
dataset
Creating A Server-Based Database
Visual Studio provides wizards that make it easy to
create and configure the database
• The Add New Item window provides a Service-based
Database option for creating an empty SQL Server database
• The default name of the SQL Server database is
Database1.mdf
• This book uses SQL Server
database as examples
The Database File's Location
When you use Visual Studio to create a SQL server
database, the database file will be created in the
project's folder
• The "project's folder" is where the Form1.cs,
Form1.Designer.cs, and Program.cs files are stored
• The file extension is .mdf. For example, Phonelist.mdf.
• The server will also create a file that ends with the .LDF
extension. For example, Phonelist_log.LDF.
• This is a transaction log file used to keep a log of all the operations
that you perform on the database
The DataGridView Control
A data-bound control is a user interface control that is connected
to a data source
It automatically displays data from the data source and can be
used to change the data
A DataGridView control is the simplest data-bound control and
can display a database table in a scrollable grid
Navigator bar
Auto-Generated Code
When you place a data-bound control, such as the DataGridView,
on a form, the following code will be generated automatically:
private void personBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.personBindingsource.EndEdit();
this.tableAdapterManager.UpdateAll(this.personDataSet);
}
•These codes execute when the user clicks the Save button on the
navigator bar
•These codes apply any changes that have been made to the dataset and
save them to the database
A Load event handler is also added to the form to call the table adatper's Fill method
private void Form1_Load(object sender, EventArgs e)
{
this.personTableAdapter.Fill(this.personDataSet.Person);
}
Connecting to an Existing Database and
Using Details View Controls
A Details view is a set of individual controls that are
bound to the columns in a single row
Rather than showing multiple rows at once, a Details
view lets the user see one row at a time
The Details view control is an alternative to the
DataGridView control for interacting with a database
Navigator bar
Detail view controls
More About Data-Bound Controls
The DataGridView control and the Details view may be
customized
In the Designer, if you select a DataGridView control, you will
see a small arrow in the upper-right corner which is called a
smart tag
If you click the smart tag, you will get a task panel with the
following options:
• Enable Adding – adds rows in the DataGridView
• Enable Editing – changes the contents of rows
• Enable Deleting – deletes rows
• Enable Column Recording – allows users to click and drag columns
to rearrange them
Customizing the Details View
By default, Details view controls are automatically bound in the
following ways:
• Columns containing character data are bound to TextBox controls
• Numeric columns are bound to TextBox controls
• Bit columns are bound to CheckBox controls
• Datetime columns are bound to DateTimePicker controls
You can customize the type of control to which column will be
bound in the Data Source window
Binding Columns to ListBox Controls
You can bind a column to a ListBox control and
display all the values in that column to be displayed
in the list box
You need to use two of ListBox control's properties:
• DataSource: identifies the table from which the ListBox will get
its data
• DisplayMember: identifies the column
Selecting Data with the SQL Select
Statement
SQL, short for structured query language, is a standard
language for working with database management systems
SQL statements consist of several keywords
• You use the keywords to construct statements known as queries
• Queries are sent to the DBMS as instructions to process data
• The SELECT and FROM statements, for example, are used for retrieving
the rows in a table. To retrieve the Description column for every row in
the Product table, use:
SELECT Description FROM Product
• SQL is not case-sensitive
In this chapter, SQL statements are part of the C# applications
you will create
The Select Statement
The SELECT statement allows you to select specific
rows. Its generic form is:
SELECT Columns FROM Table
To retrieve the Description and Price columns for
every row in the Product table, use:
SELECT Description, Price FROM Product
If you wish to retrieve every column in a table, use
the * character
SELECT * FROM Product
Specifying a Search Criteria with the
Where Clause
When you need to narrow the list down to few
selected rows in the table, use the WHERE clause
• The general format is:
SELECT Columns FROM Table WHERE Criteria
in which Criteria is a conditional expression
SELECT * FROM Product WHERE Price > 20.00
SQL supports several relational operators for writing
conditional expressions
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to
Sample SQL Statements (Where Clause)
To retrieve the product numbers and prices of all the
items that are priced at $28.95:
SELECT Product_Number, Price FROM Product WHERE Price = 28.95
To retrieve all the columns from only the rows where
the description is "Denim Jeans":
SELECT * FROM Product WHERE Description = 'Denim Jeans'
If you need to include a single quote as part of a
string, simply write two single quotes. To search for
Katy's Wool Cap, use:
SELECT * FROM Product WHERE Description = 'Katy''s Wool Cap'
SQL String Functions
SQL keywords and clauses are not case-sensitive. But, string
comparison are.
• 'Denim Jeans', 'denim jeans', and 'Denim jeans' are considered three
different string literals
• The following three SQL statements will generate three different
results:
SELECT * FROM Product WHERE Description = 'Denim Jeans'
SELECT * FROM Product WHERE Description = 'denim jeans'
SELECT * FROM Product WHERE Description = 'Denim jeans'
You can use the Lower() or Upper() string function before
performing the comparison
SELECT * FROM Product WHERE Lower(Description) = 'denim jeans'
SELECT * FROM Product WHERE Upper(Description) = 'DENIM JEANS'
Using the LIKE Operator
The LIKE operator allows you to do a search based on a pattern
rather than specifying exactly what is desired
• "Oxford Cloth Shirt" and "Poplin Shirt" both contains the string "Shirt"
• Use the string "Shirt" as the pattern with the wildcard character %
• % represents any sequence of zero or more characters
SELECT * FROM Product WHERE Description LIKE '%Shirt%'
SELECT * FROM Product WHERE Description LIKE 'Chino%'
SELECT * FROM Product WHERE Description LIKE '%jeans'
• The underscore (_) wildcard character represents a single character.
To search for all rows in which Product_Number begins with "2",
followed by any one character, followed by "-0", followed by any one
character, use
SELECT * FROM Product WHERE Product_Number LIKE '2_-0_'
Using Logical Operators
You can use the AND, OR, and NOT logical operators to
specify multiple search criteria in a WHERE clause
• The AND operator requires both search criteria be true for a row
to be qualified as a match
SELECT * FROM Product WHERE Price > 20.00 AND Price < 30.00
• The OR operator requires that either of the search criteria be
true for a row to be qualified as a match
SELECT * FROM Product WHERE Price > 20.00 OR Product_Number LIKE '10-
%'
• The NOT operator disqualify a search criteria
SELECT * FROM Product WHERE Description NOT LIKE '%Shirt%'
Sorting the Results of a Select Query
To sort the results of a SELECT query, use the ORDER
BY clause
SELECT * FROM Product ORDER BY Price
SELECT * FROM Product WHERE Price > 20.00 ORDER BY Price
• The results will be sorted in ascending order
• To sort in descending order, use the Desc operator
SELECT * FROM Product ORDER BY Price Desc
SELECT * FROM Product WHERE Price > 20.00 ORDER BY Price Desc
Table Adapter Queries
A table adapter query is an SQL statement that is stored in a table
adapter and can be executed simply by calling a method
When you place a data-bound control, such as DataGridView, on a
form, a Load event handler that calls the table adapter's Fill
method is automatically created for the form
private void MainFrom_Load(object sender, EventArgs e)
{
this.productTableAdapter.Fill(this.productDataSet.Product);
//call the Fill method
}
The above code calls the productTableAdapter's Fill method,
passing the dataset's Product table as an argument
The Fill method also fills the dataset table with rows that are
returned from a SQL statement (described in the next slide)
Table Adapter Queries (Cont'd)
• In the Solution Explorer, you will see an entry named
ProductDataSet.xsd which is the schema definition file that
describes the contents of the productDataSet (1)
• Double-click the ProductDataSet.xsd entry to open it in an editor
window (2)
• Right-click the area that reads Fill, GetData() and select
Configure from the pop-up menu to display the Table Adapter
Configuration Wizard (3)
• You can then add your own SQL queries
(1) (2) (3)
SQL Math Functions
SQL provides several functions for performing calculations
• Avg(Column): calculates the average value in a particular column
SELECT Avg(Price) FROM Product
• Sum(Column): calculates the sum of a column's values
SELECT Sum(Price) FROM Product
• Min(Column): finds the minimum value of a column.
SELECT Min(Price) FROM Product
• Max(Column): finds the maximum value of a column
SELECT Max(Price) FROM Product
• Count(Column): returns the number of values of the specified column
SELECT Count(Price) FROM Product
•To determine the number of rows in a table, use:
SELECT Count(*) FROM Product
Query Parameters
SQL queries can accept arguments
• Arguments are passed into parameter variables
• In SQL, a parameter variable begins with the @ symbol
SELECT * FROM Product WHERE Price < @priceValue
• The above statement retrieves all the rows in which the Price column is
less than the value of the priceValue parameter
• When you call the table adapter method for an SQL query, you have to
pass arguments for any parameters that are used in the query
private void searchButton_Click(object sender, EventArgs e)
{
this.productTableAdapter.SearchDesc(
this.productDataSet.Product, searchTextBox.Text);
}
• The above code calls the table adapter's SearchDesc method
• The 2nd argument is the searchTextBox control's Text property
End