Download presentation
Presentation is loading. Please wait.
1
An introduction to database programming
Based on Murach (ch 17) and Deitel 2012
2
Objectives Knowledge Describe the hardware components of a typical multi-user system. Describe the software components of a typical multi-user database application. Explain how a table in a relational database is organized. Explain how the tables in a relational database are related. Describe the use of these SQL statements: Select, Insert, Update, Delete. Describe the use of these ADO.NET components: data adapter Command Connection data reader Dataset data table Compare the structure of a dataset with the structure of a relational database. Describe concurrency, optimistic concurrency control, and “last in wins.” Describe two ways that you can create ADO.NET components.
3
A simple client/server system
4
The three hardware components of a client/server system
The clients are the PCs, Macintoshes, or workstations of the system. The server is a computer that stores the files and databases of the system and provides services to the clients. When it stores databases, it’s often referred to as a database server. The network consists of the cabling, communication lines, and other components that connect the clients and the servers of the system.
5
Client/server system implementations
In a simple client/server system, the server is typically a high- powered PC that communicates with the clients over a local area network (LAN). The server can also be a midrange system, like an IBM Power System or a Unix system, or it can be a mainframe system. Then, special hardware and software components are required to make it possible for the clients to communicate with the midrange and mainframe systems. A client/server system can also consist of one or more PC-based systems, one or more midrange systems, and a mainframe system in dispersed geographical locations. This type of system is commonly referred to as an enterprise system. Individual systems and LANs can be connected and share data over larger private networks, such as a wide area network (WAN) or a public network like the Internet.
6
Client software, server software, and the SQL interface
7
Server software To manage the network, the server runs a network operating system such as Windows Server (2018). To store and manage the databases of the client/server system, each server requires a database management system (DBMS) such as Microsoft SQL Server. The processing that’s done by the DBMS is typically referred to as back-end processing, and the database server is referred to as the back end.
8
Client software The application software does the work that the user wants to do. This type of software can be purchased or developed. The data access API (application programming interface) provides the interface between the application and the DBMS. The newest data access API is ADO.NET 4.5*, which is a part of Microsoft’s .NET Framework. The processing that’s done by the client software is typically referred to as front-end processing, and the client is typically referred to as the front end. * When the Book was published
9
The SQL interface The application software communicates with the DBMS by sending SQL queries through the data access API. When the DBMS receives a query, it provides a service like returning the requested data (the query results) to the client. SQL, which stands for Structured Query Language, is the standard language for working with a relational database.
10
Client/server versus file-handling systems
In a client/server system, the processing done by an application is typically divided between the client and the server. In a file-handling system, all of the processing is done on the clients. Although the clients may access data that’s stored in files on the server, none of the processing is done by the server. As a result, a file-handling system isn’t a client/server system.
11
The Products table in the MMABooks database
Primary Keys
12
How a table is organized
A relational database uses tables to store and manipulate data. Each table consists of one or more records, or rows, that contain the data for a single entry. Each row contains one or more fields, or columns, with each column representing a single item of data. Most tables contain a primary key that uniquely identifies each row in the table. Some database management systems let you define one or more non-primary keys. In SQL Server, these keys are called unique keys, and they’re implemented using unique key constraints. A table can also be defined with one or more indexes. An index provides an efficient way to access data from a table based on the values in specific columns. An index is automatically created for a table’s primary and non-primary keys. work
13
TwPo related tables: Invoices and InvoiceLineItems
PK FK
14
How the tables in a database are related
The tables in a relational database are related to each other through their key columns. A column that identifies a related row in another table is called a foreign key. Usually, a foreign key corresponds to the primary key in the related table. In SQL Server, however, a foreign key can also correspond to a unique key in the related table. When two tables are related via a foreign key, the table with the foreign key is referred to as the foreign key table and the table with the primary key is referred to as the primary key table. The relationships between the tables in a database correspond to the relationships between the entities they represent. The most common type of relationship is a one-to-many relationship. A table can also have a one-to-one relationship or a many-to- many relationship with another table.
15
The Server Explorer design view window for the Invoices table
16
More details (Data Types)
The data type that’s assigned to a column determines the type of information that can be stored in the column. Depending on the data type, the column definition can also include its length, precision, and scale. Each column definition also indicates whether or not the column can contain null values. A null value indicates that the value of the column is not known. A column can be defined with a default value. Then, that value is used for the column if another value isn’t provided when a row is added to the table. A column can also be defined as an identity column. An identity column is a numeric column whose value is generated automatically when a row is added to the table. To restrict the values that a column can hold, you define check constraints. Check constraints can be defined at either the column level or the table level. Note When you select a column in design view, its properties are displayed in the Properties window. Then, you can use this window to change any of the properties of the column, including those that aren’t displayed in design view.
17
Common SQL Server data types
18
The tables that make up the MMABooks database (see ch. 23)
19
MMABooks Tables The Customers table contains a row for each customer.
Its primary key is CustomerID, an identity State is a foreign key that relates each customer to a row in the States table. The Invoices table contains a row for each invoice. Its primary key is InvoiceID, an identity column CustomerID is a foreign key that relates each invoice to a customer. The InvoiceLineItetns table contains one row for each line item of each invoice. Its primary key is a combination of InvoiceID and ProductCode. InvoiceID is a foreign key that relates each line item to an invoice. and ProductCode is a foreign key that relates each line item to a product.
20
MMABooks Tables The Products table contains a row for each product.
Its primary key is ProductCodeID a 10-character code that identifies each product. The States table contains a row for each state. Its primary key is StateCode. The OrderOptions table contains a single row that stores the sales tax and shipping charges used by the application. The relationships between the tables in this diagram appear as links, where the end points indicate the type of relationship. A key indicates the “one” side of a relationship, and the infinity symbol (00) indicates the “many” side.
21
Queries: Simplified syntax of the Select statement
Select column-1 [, column-2]... From table-1 [Where selection-criteria] [Order By column-1 [Asc|Desc] [, column-2 [Asc|Desc]]...]
22
A Select statement that retrieves and sorts selected columns and rows from the Customers table
Select Name, City From Customers Where State = 'WA' Order By Name
23
How to query a single table
The result of a Select statement is a result table, or result set,. The Select clause lists the columns to be included in the result set. This list can include calculated columns that are calculated from other columns. The From clause names the table the data will be retrieved from. The Where clause specifies which rows should be retrieved. To retrieve all rows from a table, omit the Where clause. The Order By clause lists the columns that the results are sorted by and indicates whether each column is sorted in ascending or descending sequence. To select all of the columns in a table, you can code an asterisk (*) in place of the column names: Select * From Customers
24
The syntax of the Select statement for joining two tables
Select column-list From table-1 [Inner] Join table-2 On table-1.column-1 {=|<|>|<=|>=|<>} table-2.column-2 [Where selection-criteria] [Order By column-list]
25
A Select statement that joins data from the InvoiceLineItems and Products tables
Select InvoiceLineItems.InvoiceID, InvoiceLineItems.ProductCode, Products.Description, InvoiceLineItems.UnitPrice, InvoiceLineItems.Quantity From InvoiceLineItems Inner Join Products On InvoiceLineItems.ProductCode = Products.ProductCode Where InvoiceID = 46
26
How to join data from two or more tables
A join lets you combine data from two or more tables into a single result set. The most common type of join is an inner join. This type of join returns rows from both tables only if their related columns match.
27
Inner Join When you use an inner join, rows from the two tables in the join are included in the result set only if their related columns match. These matching columns are specified in the From clause of the Select statement Ex.: rows from the InvoiceLineItems and Products tables are included only if the value of the ProductCode column in the Products table matches the value of the ProductCode column in one or more rows in the InvoiceLineItems table. Notice that each column in the Select clause is qualified to indicate which table the column is to be retrieved from. For example, the InvoiceID, ProductCode, UnitPrice, and Quantity columns are retrieved from the InvoiceLineItems table, but the Description column comes from the Products table. Qualification is only required for columns that exist in both tables. In this case, only the ProductCode column requires qualification because both the InvoiceLineItems and the Products tables have a column named ProductCode .
28
Inner Join cont. However, it is recommended that you qualify all of the columns just to make it clear which table each column is being retrieved from. Although this figure shows how to join data from two tables, you should know that you can extend this syntax to join data from additional tables. If, for example, you want to include data from the Invoices table along with the InvoiceLineItems and Products data, you could code a From clause like this: From Invoices Inner Join InvoiceLineItems On Invoices.InvoiceID = InvoiceLineItems.InvoiceID Inner Join Products On InvoiceLineItems.ProductCode = Products.ProductCode Then, in the column list of the Select statement, you can include any of the columns in the Invoices, InvoiceLineItems, and Products tables.
29
The syntax of the Insert statement for adding a single row
Insert [Into] table-name [(column-list)] Values (value-list) A statement that adds a single row to the Products table Insert Into Products (ProductCode, Description, UnitPrice, OnHandQuantity) Values ('CS15', 'Murach''s C# 2015', 56.50, 3000) SINGLE QUOTES FOR STRINGS
30
The syntax of the Update statement
Update table-name Set expression-1 [, expression-2]... [Where selection-criteria] A statement that updates the UnitPrice column for a specified product Update Products Set UnitPrice = 54.00 Where ProductCode = 'MCCP'
31
The syntax of the Delete statement
Delete [From] table-name [Where selection-criteria] A statement that deletes a specified customer Delete From Customers Where CustomerID = 558
32
ADO.NET ADO.NET (ActiveX Data Objects .NET) is the primary data access API for the .NET Framework. It provides the classes that you use as you develop database applications with C# as well as other .NET languages. These classes can be divided into two categories: 1) the .NET data providers, which provide the classes that you use to access the data in a database, 2) and datasets, which provide the classes that you use to store and work with data in your applications.
33
Data provider core objects
NET Data Providers provide ADO.NET classes are responsible for working directly with a database.
34
Data providers included with the .NET Framework
35
Odbc, OleDb, SQLClient System.Data.SQLClient System.Data.OledbClient
Connects to SQL Server 2000 and later only, but you will get optimal performance when connecting to those databases. System.Data.OledbClient Connects to SQL 6.5 OLEDBClient gives you ability to connect to other database like ORACLE or Access. But for working with SQL Server you will get better performance using SQLClient. Note: For connecting to ORACLE, Microsoft also has ORACLEClient. System.Data.ODBCClient Connects to legacy databases only, using ODBC drivers. (E.g. MS Access 97.)
36
Class names for the data providers
A using directive for the SQL Server data provider namespace using System.Data.SqlClient;
37
Data Providers Summary
The .NET data providers provide the ADO.NET classes that are responsible for working directly with a database. In addition to the core classes (e.g. SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter), classes are provided for other functions such as passing parameters to commands or working with transactions. To use a .NET data provider in a program, you should add a using directive for the appropriate namespace at the beginning of the source file.
38
Basic ActiveX Data Object (ADO.NET ) components
L I C T O N Data used by apps MS SQL Oracle DB2 Excel …
39
Disconnected Data Architecture
The data used by applications is stored in datasets (object) that contains one+ data tables. Application can insert, update, delete rows in the data tables. Data Adapters are used to retrieve data from the database and load it into a data table. Ex. Retrieve Data. Data Adapter object issues a Select statement, that is stored in command object. Command object uses a connection object to connect to that databases and retrieve the data. Then, data is passed back to the adapter, which stores the data in a table within the dataset.
40
Data Adapters The main function of the data adapter is to manage the flow of data between a dataset and a database. To do that, it uses command that define the SQL statements to be issued. The command for retrieving data, for example, typically defines a Select statement. Then, the command connects to the database using a connection and passes the Select statement to the database. After the Select statement is executed, the result set it produces is sent back to the data adapter, which stores the results in the data table. To update the data in a database, the data adapter determines which rows in the data table have been inserted, updated, or deleted. Then, it uses commandst hat define Insert, Update, and Delete statements for the data table to update the associated rows in the database. Like the command that retrieves data from the database, the commands that update the database use a connection to connect to the database and perform the requested operation.
41
Disconnected Data Architecture cont.
Data provider remains connected to the database only long enough to retrieve or update the specified data. Then, it disconnects from the database an the application works with the data via dataset object. Disconnected Data Architecture – improves system resource utilization. Same for Update and Delete Data Dataset is independent of the DB. Connection to DB usually closed after retrieving data. Application is working with a copy of data (Disconnected Data Architecture)
42
Two users who are working with copies of the same data
Disadvantage of Disconnected Data Architecture
43
Concurrency concepts When two or more users retrieve the data in the same row of a database table at the same time, it is called concurrency. Because ADO.NET uses a disconnected data architecture, the database management system can’t prevent this from happening. If two users try to update the same row in a database table at the same time, the second user’s changes could overwrite the changes made by the first user. Whether or not that happens, though, depends on the concurrency control that the programs use. By default, ADO.NET uses optimistic concurrency. This means that the program checks to see whether the database row that’s going to be updated or deleted has been changed since it was retrieved. If it has, a concurrency exception occurs and the update or deletion is refused. Then, the program should handle the exception.
44
Concurrency concepts cont.
If optimistic concurrency isn’t in effect, the program doesn’t check to see whether a row has been changed before an update or deletion takes place. Instead, the operation proceeds without throwing an exception. This is referred to as “last in wins” because the last update overwrites any previous update. And this can lead to errors in the database.
45
How to avoid concurrency errors
For many applications, concurrency errors rarely occur. As a result, optimistic concurrency is adequate. If concurrency is likely to be a problem, a program that uses a dataset can be designed so it updates the database and refreshes the dataset frequently. That way, concurrency errors are less likely to occur. Another alternative is to design a program so it retrieves and updates just one row at a time. That way, there’s less chance that two users will retrieve and update the same row at the same time.
46
The basic dataset object hierarchy
Structured like relational database But NOT exactly because of join and selected columns/rows
47
Dataset A dataset object consists of a hierarchy of one or more data table and data relation objects. A data table object consists of one or data column objects and one or more data row objects. The data column objects define the data in each column of the table, including its name, data type, and so on, and the data row objects contain the data for each row in the table. A data table can also contain one or more constraint objects that are used to maintain the integrity of the data in the table. A unique key constraint ensures that the values in a column, such as the primary key column, are unique. And a foreign key constraint determines how the rows in one table are affected when corresponding rows in a related table are updated or deleted. The data relation objects define how the tables in the dataset are related. They are used to manage constraints and to simplify the navigation between related tables. All of the objects in a dataset are stored in collections. For example, the data table objects are stored in a data table collection, and the data row objects are stored in a data row collection. You can refer to these collections through properties of the containing objects.
48
Dataset != Table Although a dataset is structured much like a relational database, it’s important to realize that each table in a dataset corresponds to the result set that’s returned from a Select statement, not necessarily to an actual table in a database. For example, a Select statement may join data from several tables in a database to produce a single result set. In this case, the table in the dataset would represent data from each of the tables involved in the join.
49
ADO.NET components for accessing a database directly w/o Adapter
50
ADO.NET components for accessing a database directly without data adapter (ch 17)
Return rows, read forward only no adapter Executing Commands Directly Handle the results: Insert, Delete, Update return int (how many rows affected, determining success)
51
Direct Access w/o Adapter
When you want to work with two or more rows from a database at the same time, you typically use a data adapter to retrieve those rows and store them in a dataset. Can be done w/o without using a data adapter. You still use command and connection objects to access the database. Instead of using a data adapter to execute the commands, though, you execute the commands directly. When you do that, you also have to provide code to handle the result of the command. If you issue a command that contains an Insert, Update, or Delete statement, for example, the result is an integer that indicates the number of rows that were affected by the operation. You can use that information to determine if the operation was successful. If you execute a command that contains a Select statement, the result is a result set that contains the rows you requested. To read through the rows in the result set, you use a data reader object. Although a data reader provides an efficient way of reading the rows in a result set, you can’t use it to modify those rows. In addition, it only lets you read rows in a forward direction. Once you read the next row, the previous row is unavailable. Because of that, you typically use a data reader to retrieve and work with a single database row at a time.
52
Two ways to create ADO.NET objects
1. way using Data Source (drag–and-drop) First, you can create ADO.NET objects from a data source listed in the Data Sources window. Data sources make it easy to quickly create forms that work with the data in a data source such as a database.
53
ADO.NET objects created using the Data Sources window
Ex.: the data source corresponds with the data in the Products table in the MMABooks database.
54
Objects Details Five (5) objects have been added to the Component Designer tray below the form. Three of these are ADO.NET objects. 1) mMABooksDataSet, defines the dataset for the form. 2) productsTableAdapter defines the table adapter for the Products table. A table adapter is similar to a data adapter, but it can only be generated by the designer. 3) tableAdapterManager makes sure that if two or more related tables are updated by the form, referential integrity is maintained. The other two objects in the Component Designer tray are used to bind the controls on the form to the data source. 4) productsBindingSource, identifies the Products table as the data source for the controls. 5) productsBindingNaVigator, defines the toolbar that’s displayed across the top of the form.
55
Objects Details Although you don’t usually need to change the properties of the objects in the Component Designer tray, you should know that you can do that using the same technique you use to change the properties of a control on a form. That is, you just select an object to display its properties in the Properties window and then work with them from there.
56
ADO.NET objects created using code
string connectionString = "Data Source=localhost\\SqlExpress;Initial Catalog=MMABooks;" + "Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); string selectStatement = "SELECT * FROM Products ORDER BY ProductCode"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); SqlDataAdapter productsDataAdapter = new SqlDataAdapter(selectCommand); DataSet productsDataSet = new DataSet();
57
Code ADO.NET Although creating ADO.NET objects through code is more time-consuming han using data sources, it can result in more compact and efficient code. In addition, creating ADO.NET objects through code lets you encapsulate an application’s database processing in specialized database classes.
58
AirlineReservation Db connection
private SqlConnection connectToDatabase() { SqlConnection con = new 18\AirlineReservation3\AirlineReservation\AirlineReservationDb .mdf;Integrated Security=True"); return con; }
59
Save seats SqlConnection con = null; try { con = connectToDatabase(); if (con != null) { con.Open(); } SqlCommand deleteCommand = new SqlCommand("DELETE FROM SeatsTable", con); // //simple: delete first int rowsDeleted = deleteCommand.ExecuteNonQuery(); for (int i = 0; i < seats.Length; i++) { SqlCommand insertCommand = new SqlCommand("INSERT INTO SeatsTable (seatNumber, con); SqlDbType.Int).Value = i; SqlDbType.Bit).Value = seats[i]; int rowsInserted = insertCommand.ExecuteNonQuery(); Console.WriteLine("Saved seat {0} reserved {1} ", i, seats[i]); return true; catch (SqlException ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); return false; finally { con.Close();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.