0% found this document useful (0 votes)
2 views99 pages

Lecture Notes On Database For Web Applications

This document outlines the learning objectives and importance of studying databases for web applications, focusing on the architecture of four-tier web applications and the role of databases in dynamic content management. It covers SQL database design, server-side programming with various technologies, and best practices for secure database interactions. Additionally, it provides examples of database programming languages and APIs, emphasizing the integration of databases in modern web applications.

Uploaded by

manderaben9371
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views99 pages

Lecture Notes On Database For Web Applications

This document outlines the learning objectives and importance of studying databases for web applications, focusing on the architecture of four-tier web applications and the role of databases in dynamic content management. It covers SQL database design, server-side programming with various technologies, and best practices for secure database interactions. Additionally, it provides examples of database programming languages and APIs, emphasizing the integration of databases in modern web applications.

Uploaded by

manderaben9371
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Database

for
Web Applications
Learning Objectives
By the end of this lesson, students should be able to:
1. Explain the architecture of a four-tier web application, emphasizing the role
of databases in dynamic content management.
2. Design and implement relational databases using SQL, including DDL, DML,
and query statements.
3. Demonstrate server-side database programming with technologies such as
PHP, JSP, ASP.NET, and Ruby on Rails.
4. Utilize ADO.NET, JDBC, or PHP APIs to connect, query, and manage
database operations within web applications.
5. Evaluate the trade-offs between different data access patterns, including
DataReader vs. DataSet, and stateless vs. persistent connections.
6. Implement secure and transactional database interactions, using best
practices such as exception handling, connection pooling, and rollback
mechanisms.
Why Do We Study Databases for Web
Applications
Studying databases for web applications is essential for Computer Science and
Software Engineering students because:
1. Modern web applications are data-driven. They rely on persistent storage to
manage user data, content, transactions, and analytics.
2. Understanding SQL and database design enables students to create robust
backends and manipulate data effectively.
3. Databases are integral to web application architecture, often interacting with
the presentation, logic, and storage layers in multi-tier systems.
4. Students learn cross-platform programming interfaces (e.g., PHP, ASP.NET,
JSP) that integrate with databases using APIs and data providers.
5. Database programming fosters skills in concurrency, transactions, and data
integrity, essential for building scalable and secure enterprise applications.
6. It bridges theoretical knowledge and real-world applications, preparing
students for roles in full-stack development, data engineering, and cloud
solutions.
Introduction
to
Web Applications
Architecture of a Four-Tier Web Application

Supporting Software
App User Interface (V)
WEB WEB
User Interface
S C
Application Logic (C) E L
Database Engine R I
V E
Database Database API (M) E N
R T

DBMS / Database Server Application Server

Architecture of a Four-Tier Web Application


Introduction to Database
Definitions
§ Computer Science: the science of data processing using
a computational device.
§ Database (DB): a persistent store of data in a compact,
secure, easy-and-fast-to-retrieve form.
§ Database Engine: a software program that creates and
.
manages databases. (e.g. MS Jet Engine)
§ Database Management System (DBMS): a database
engine plus user interfaces and other supporting software.
§ DBMS Examples: Oracle, DB2 (IBM), Sybase, Informix,
Microsoft SQL Server, Microsoft Access, MySQL (public
domain), …
§ Database Server: a DBMS that provides data to its
remote clients.
DBMS Example: SQL Server
• By Microsoft
• Needs runtime license
• Best fit for .NET
• Features
http://www.microsoft.com/sql/prodinfo/features/top30features.mspx
• Available in MSDNAA.
http://www.cs.uakron.edu/~xiao/msdnaa.html
• Free-for-all version: SQL Server Express
http://www.microsoft.com/sql/editions/express/default.mspx
DBMS Example: MySQL
• By MySQL AB (part of Sun after 1/16/08.
Sun has been merged into Oracle.)
• Free: http://dev.mysql.com/
• No need of runtime license
• Not the best fit for .NET
MySQL on db1.cs.uakron.edu
• MySQL is used for the following classes:
Windows Programming, Internet System Programming,
Introduction to Database, Data Mining, and Data Integration.
• It has been installed on db1.cs.uakron.edu
• To use it, follow the instructions at
http://www.cs.uakron.edu/~xiao/windows/4T-App-
Deployment.html
• To install it at home, follow the instructions at
http://www.cs.uakron.edu/~xiao/windows/MySQL-
Installation.html
Data Format in the Database

§ Database Table: data are stored in a database as


“tables”. Each row of a table is called a record, each
column of a table is called an attribute. Each needs to
have a “key” attribute(s). Each record needs to have a
unique key value.
PhoneBook (Database Table Name)

Name Office Home Cell


Tom 330-972-5809 330-888-8888 330-168-8888
John 330-972-7777 330-777-7777 330-168-7777
… … … …

§ Database schema: meta data for databases, defining


tables and their attributes.
Database Schema, Language, API

§ Database schema: meta data for databases, defining


tables and their attributes. (UDT, like classes)

§ SQL (Structured Query Language): the de facto standard


language for database.

§ Database API: application programming interface to


DBMSs.
SQL

§ SQL: Structured Query Language, a standardized


language for accessing and manipulating databases.

§ The Select-From-Where Clause:


Select Office From PhoneBook Where Name=’Tom’;
Select * From PhoneBook;

§ Three Parts of SQL:


§ Query: data retrieval
§ DML - Data Manipulation Language: inserting, deleting, updating, …
§ DDL - Data Definition Language: table creation, alteration and drop.
SQL Example
CREATE DATABASE pubs;
USE pubs;
CREATE TABLE authors
(
au_id varchar(11) NOT NULL,
au_lname varchar(40) NOT NULL,
au_fname varchar(20) NOT NULL,
phone char(12) NOT NULL DEFAULT 'UNKNOWN',
address varchar(40) NULL,
city varchar(20) NULL,
state char(2) NULL,
zip char(5) NULL,
contract bit NOT NULL,
PRIMARY KEY(au_id)
);
SQL Example
insert authors
values('409-56-7008', 'Bennet', 'Abraham', '415 658-9932',
'6223 Bateman St.', 'Berkeley', 'CA', '94705', 1);

insert authors
values('213-46-8915', 'Green', 'Marjorie', '415 986-7020',
'309 63rd St. #411', 'Oakland', 'CA', '94618', 1);
Server-Side
Database Programming
Architecture of a Four-Tier Web Application

Supporting Software
App User Interface (V)
WEB WEB
User Interface
S C
Application Logic (C) E L
Database Engine R I
V E
Database Database API (M) E N
R T

DBMS / Database Server Application Server

Architecture of a Four-Tier Web Application


Pattern of database programming
§ Create a connection object.
§ Open the connection.
§ Create a command object.
§ Execute the command.
§ Access the data.
n Close the connection.
Server-Side
Database
Programming Languages
Database Programming Languages

PHP
JSP / Servlet
ASP.NET
Roby on Rails
Database Programming
with PHP
PHP DB Programming
https://www.php.net/
https://www.w3schools.com/php/default.asp
Programming PHP
https://www.php.net/manual/en/features.commandline.webs
erver.php

Examples (needs to be on UA VPN)


http://www.cs.uakron.edu/~xiao/isp/PHP-HowTo.html
http://pausch.cs.uakron.edu/~xiao/php/db-starter.html
Database Programming
with JSP
JSP DB Programming

JavaServer Page (JSP) Introduction


How to Run JSP Programs on the Lab Computers
Java Web Server Setup
JSP Examples (needs to be on UA VPN)
http://pausch.cs.uakron.edu:8080/xiao/cars.jsp

https://www.tutorialspoint.com/jsp/
Java Web Application Server Setup
http://java.sun.com/products/jsp/jstl/
http://java.sun.com/j2ee/
Database Programming
with ASP.NET
Microsoft ADO .NET
ADO.NET is the database API for managed applications
(application servers) to talk to database servers (DBMS:
Database Management Systems).
§ a database API for managed applications;
§ a set of classes in .NET FCL System.Data namespace;
§ designed to work over the Web;
§ integrates effortlessly with XML;
§ maps very well to stateless, text-based protocol HTTP;
§ accesses databases through modules known as data
providers ( a set of APIs that make the accesses easy to
program).
Two Data Providers
1. The SQL Server .NET provider
§ interfaces to Microsoft SQL Server (7.0 or later)
§ all managed code
§ code runs faster
§ code not portable to other databases
2. The OLE DB .NET provider
§ OLE: Object Linking and Imbedding
§ interfaces to databases through unmanaged OLE
DB providers: SQLOLEDB for SQL Server (6.5 or
earlier), MSDAORA for Oracle and Microsoft,
Jet.OLEDB.4.0 for Microsoft Jet database engine.
§ code runs slower
§ code portable to other databases
The System.Data.SqlClient and System.Data.OleDb Namespaces

Classes in System.Data.SqlClient are for SQL Server .NET


using System.Data.SqlClient;
SqlConnection conn = new SqlConnection
("server=localhost;database=pubs;uid=sa;pwd=");
try { conn.Open ();
SqlCommand cmd = new SqlCommand ("select * from titles",
conn);
SqlDataReader reader = cmd.ExecuteReader ();
while (reader.Read ()) Console.WriteLine (reader["title"]);
} catch (SqlException ex) {
Console.WriteLine (ex.Message);
} finally { conn.Close (); }
The System.Data.SqlClient and System.Data.OleDb Namespaces

Classes in System.Data.OleDb are for OLE DB .NET


using System.Data.OleDb;
OleDbConnection conn = new
OleDbConnection("provider=sqloledb;server=localhost;dat
abase=pubs;uid=sa;pwd=");
try { conn.Open ();
OleDbCommand cmd =
new OleDbCommand ("select * from titles", conn);
OleDbDataReader reader = cmd.ExecuteReader ();
while (reader.Read ()) Console.WriteLine (reader["title"]);
} catch (OleDbException ex) {
Console.WriteLine (ex.Message);
} finally { conn.Close (); }
Pattern of database programming
§ Create a connection object.
§ Open the connection.
Connection Objects
The SqlConnection Class
The ConnectionString

SqlConnection conn = new SqlConnection ();


conn.ConnectionString =
"server=localhost;database=pubs;uid=sa;pwd=";
or
SqlConnection conn = new SqlConnection
("server=localhost;database=pubs;uid=sa;pwd=");

Errors in the connection string only throws exceptions at


runtime.
Server
Server
Server=localhost or Server=(local) or Data Source=(local)

SQL Server permits different instances of servers to be


installed on a given machine.

server=db1 (an database server computer named “db1” at


the CS department of UA)

server=hawkeye\wintellect (an instance of SQL Server


named Wintellect on a remote machine named Hawkeye)

Database or Initial Catalog: database name (e.g. Pubs)


UID or User ID, Pwd: tempdb, tempdb
Server
§ Min Pool Size and Max Pool Size, the size of the
connection pool (the defaults are 0 and 100)
§ Integrated Security: default to false, otherwise uses
Windows access tokens for authentication.
§ Connect Timeout: how many seconds to wait for a
connection to open (default=15).

SqlConnection conn = new SqlConnection


("server=hawkeye\wintellect;database=pubs;uid=sa;pwd=;"
+
"min pool size=10;max pool size=50;connect timeout=10");
Exceptions and Closing Open Connections
§ Exceptions should never go uncaught, and open
connections should always be closed before terminating.
(Calling Close on a connection that’s not open isn’t
harmful.)
SqlConnection conn = new SqlConnection
("server=localhost;database=pubs;uid=sa;pwd="); //before try block
try {conn.Open ();
// TODO: Use the connection
}
catch (SqlException e) {
Console.WriteLine (e.Message);
// TODO: Handle the exception
}
finally { conn.Close ();}
Pattern of database programming
§ Create a connection object.
§ Open the connection.

§ Do not hardcode the connection string in your code. Use


web.config and session cache to allow customization.
A mini enterprise application
Congo (C9)
Congo: A virtual storefront for an online bookseller.
Related to: database => data grid => shopping cart
Forms: Database supported, web based security.

Examples\C9\Congo-MySQL
http:/winserv1.cs.uakron.edu/xiaotest/Congo/Congo.aspx

Deployment:
http://www.cs.uakron.edu/~xiao/windows/4T-App-Deployment.html

Output format in C#
http://blog.stevex.net/string-formatting-in-csharp/
Structure of an ASP.NET Web Application

An ASP.NET application.

§ The Web.config File


To support XCOPY installs— to install applications by
copying them to a directory and uninstall them by
deleting the files and directories.
Web.config

Strings defined in the .config file can be retrieved in the program at


run time:
string conn = ConfigurationSettings.AppSettings ["MyConnectionString"];

<!-- Web.Config Configuration File -->


<configuration>
<appSettings>
<add key="MyConnectionString"
value="server=db1; database=pubs; uid=sa; pwd=" />
<add key="connectString"
value="Integrated Security=true;Initial Catalog=pubs;
Data Source=XIAO-T23-01" />
</appSettings>
</configuration>
Pattern of database programming
§ Create a connection object.
§ Open the connection.
§ Create a command object.
§ Execute the command.
Connections, Commands, and DataReaders
n Connection objects represent physical connections to a
database.
SqlConnection or OleDbConnection
n Command objects represent the commands performed
on a database.
SqlCommand or OleDbCommand
n DataReader objects represent the data obtained by the
commands.
SqlDataReader or OleDbDataReader
Command Classes: SqlCommand and OleDbCommand.
– Encapsulate SQL commands performed on a database.
– Rely on connections established.
– Include methods to execute the commands
encapsulated inside.

Example, delete a record from the Pubs database’s “Titles”


table using an SQL DELETE command:

SqlCommand cmd = new SqlCommand


("delete from titles where title_id = 'BU1032'", conn);
cmd.CommandTimeout = 10; // Allow 10 seconds, default 30.
cmd.ExecuteNonQuery (); // Execute the command
The ExecuteNonQuery Method
n For executing DML and DDL commands: CREATE, INSERT, UPDATE,
DELETE, …
n Not getting any data back.
n Examples:

SqlCommand cmd = new SqlCommand


("create database MyDatabase", conn);
cmd.ExecuteNonQuery ();

SqlCommand cmd = new SqlCommand


("create table titles …", conn);
cmd.ExecuteNonQuery ();

SqlCommand cmd = new SqlCommand


("insert into titles (title_id, title, type, pubdate) " +
"values ('JP1001', 'Programming Microsoft .NET', " +
"'business', 'May 2002')", conn);
cmd.ExecuteNonQuery ();
The ExecuteNonQuery Method
SqlCommand cmd = new SqlCommand
("update titles set title_id = 'JP2002' " +
"where title_id = 'JP1001'", conn);
cmd.ExecuteNonQuery ();

SqlCommand cmd = new SqlCommand


("delete from titles where title_id = 'JP2002'", conn);
cmd.ExecuteNonQuery ();
The ExecuteScalar Method

Executes a query command and returns a single value in the


result set, such as COUNT, AVG, MIN, MAX, and SUM.

SqlCommand cmd = new SqlCommand


("select min (price) from titles", conn);
decimal amount = (decimal) cmd.ExecuteScalar ();
Console.WriteLine ("ExecuteScalar returned {0:c}", amount);
The ExecuteScalar Method
u Another common use for ExecuteScalar is to retrieve
BLOBs (binary large objects) from databases.
u For example, retrieving an image from the “Logo” field of the
Pubs database’s “Pub_info” table and encapsulates it in a
bitmap:

use System.IO;
use System.Drawing;
use System.Data.SqlClient;
SqlCommand cmd = new SqlCommand
("select logo from pub_info where pub_id='0736'", conn);
byte[] blob = (byte[]) cmd.ExecuteScalar ();
stream.Write (blob, 0, blob.Length);
Bitmap bitmap = new Bitmap (stream);
stream.Close ();
Write a BLOB to a database.
FileStream stream = new FileStream("Logo.jpg",
FileMode.Open);

byte[] blob = new byte[stream.Length];


stream.Read (blob, 0, (int) stream.Length);
stream.Close ();

SqlCommand cmd = new SqlCommand


("insert into pub_info (pub_id, logo) values ('9937', @logo)",
conn);
cmd.Parameters.Add ("@logo", blob);

cmd.ExecuteNonQuery ();
The ExecuteReader Method
§ For performing database queries and obtain the results as
quickly and efficiently as possible.
§ Returns a DataReader object.
§ Pulls back only the data to be “Read” by the DataReader
not all records satisfying the query condition.

SqlCommand cmd = new SqlCommand ("select * from titles", conn);


SqlDataReader reader = cmd.ExecuteReader ();
while (reader.Read ()) Console.WriteLine (reader["title"]);

§ Each call to “Read” returns one row from the result set.
§ It uses a property indexer to extract the value of the
record’s “title” field.
§ Fields can be referenced by name or by numeric index (0-
based).
DataReader
§ Reads data.
§ Reads schema (meta data) .
§ Stream-based access to the results of database queries.
§ Fast and efficient.
§ Read-only and forward-only.
§ Closing a DataReader: reader.Close( )
does NOT close the connection, only frees it for others
to use.
§ D-E-F-E-N-S-I-V-E P-R-O-G-R-A-M-M-I-N-G.
DataSets
p Set-based Database Accesses
§ capture an entire query in memory
§ support backward and forward traversal
§ edit data and propagate the changes back to the
database.
DataSet, DataTable and DataAdapter
p .NET supports set-based database accesses
through three classes:

§ DataSet: equivalent of an in-memory database.


It consists of a collection of DataTables.

§ DataTables are created by a DataAdapter


(SqlDataAdapter and OleDbDataAdapter).

§ DataSet doesn’t interact with databases directly.


DataAdapter reads the physical data sources and fills
DataTables and DataSets
DataSets vs. DataReaders
§ To simply query a database and read through the records
one at a time until you find the one you’re looking for, then
DataReader is the right tool. DataReaders (1) retrieve
only the data that you actually use, and (2) they don’t
consume memory by not storing every record that you
read, but (3) they can’t iterate backward.

§ To use all the query results and to iterate backward and


forward through a result set, or to cache the result set in
memory, use a DataSet.

§ Many controls that support DataSets are perfectly capable


of binding to DataReaders.
DataGrid (GUI)

• DataGrid is an ASP control for displaying


datasets.
• Database displaying procedure:
– Use DataAdapter to get data from the
database.
– Fill the data into a DataSet
– Bind the DataSet to a DataGrid
– Select the fields (columns) to be displayed and
their header texts.
Example:
DataAdapter, DataSet and DataGrid (GUI)

<asp:DataGrid ID="MyDataGrid"
OnItemCommand="OnItemCommand" RunAt="server">
<Columns>
<asp:BoundColumn HeaderText="Title"
DataField="title" />
<asp:BoundColumn HeaderText="Price"
DataField="price" DataFormatString="{0:c}"/>
<asp:ButtonColumn HeaderText="Action"
Text="Add to Cart" CommandName="AddToCart" />
</Columns>
</asp:DataGrid>

Examples/C9/Congo-MySQL/ViewCart.aspx
Example:
DataAdapter, DataSet and DataGrid (GUI)

void Page_Load (Object sender, EventArgs e)


{
if (!IsPostBack) {
string ConnectString =
ConfigurationSettings.AppSettings["connectString"];
MySqlDataAdapter adapter = new MySqlDataAdapter
("select * from titles where price != 0", ConnectString);
DataSet ds = new DataSet ();
adapter.Fill (ds);
MyDataGrid.DataSource = ds;
MyDataGrid.DataBind ();//Bind data to GUI
}
}
Transaction Commands
§ A transaction is a logical unit of operations grouped
together.

§ If one of the operations fails, the others will fail (or be


rolled back).

§ Distributed transactions — transactions that span two or


more databases.

§ The .NET Framework supports distributed transactions.

§ The .NET supports local transactions (one database):


Transaction Commands
// Start a local transaction
trans = conn.BeginTransaction (IsolationLevel.Serializable);
// Create and initialize a SqlCommand object
SqlCommand cmd = new SqlCommand ();
cmd.Connection = conn;
cmd.Transaction = trans;
// Debit $1,000 from account 1111
cmd.CommandText = "update accounts set balance = " +
"balance - 1000 where account_id = '1111'";
cmd.ExecuteNonQuery ();
// Credit $1,000 to account 2222
cmd.CommandText = "update accounts set balance = " +
"balance + 1000 where account_id = '2222'";
cmd.ExecuteNonQuery ();
// Commit the transaction (commit changes)
trans.Commit ();
Transaction Commands
§ IsolationLevel.Serializable locks down the records while
they’re updated so that they can’t be read or written.

§ Committing the transaction writes the changes to the


database.
Uses DataGrid to represent a DataSet in XML

DataSet ds = new DataSet ();


ds.ReadXml (Server.MapPath ("Bonuses.xml"));
MyDataGrid.DataSource = ds;
Database Programming
with RoR
Architecture of RoR Web Applications

Supporting Software
App User Interface WEBrick
(View) Web
User Interface
C
Application Logic L
Database Engine (Controller) I
or any E
Database Database API Web Server N
(Model:ORM) on the same T
system.
DBMS / Database Server RoR Web Applications

Architecture of RoR Web Applications


.
Installing Rails
Rails Installation
§ Rails comes with Ruby along with RubyGems
§ PWWW uses SQLite3 (SQLite.org) for database
§ Command line installations

. gem install sqlite3


gem install rails

Or

sudo gem install sqlite3


sudo gem install rails
Rails Server Startup
Start the webrick server (came with Rails)

rails server webrick

. URL to access the server

http://localhost:3000/
Rails Hosting
§ http://www.railshosting.org/free-rails-hosting

§ https://www.airpair.com/ruby-on-rails/posts/rails-host-
comparison-aws-digitalocean-heroku-engineyard
.

§ https://www.heroku.com/

§ http://api.rubyonrails.org/

Detailed instructions on using Amazon AWS Cloud:


http://dsaigoud.com/amazon-aws-instance-setup-and-
j2ee-app-deployment.jsp
.
Programming RoR
RoR Web Application Development

§ Automatically generates web apps

. § Apps are composed of MVC classes

§ No GUI, everything is Command Line


.
RoR Web Application Development
A “Hello World” Example
Architecture of RoR Web Applications

Supporting Software
App User Interface WEBrick
(View) Web
User Interface
C
Application Logic L
Database Engine (Controller) I
or any E
Database Database API Web Server N
(Model:ORM) on the same T
system.
DBMS / Database Server RoR Web Applications

Architecture of RoR Web Applications


Programming RoR: Examples
>rails new greet

.
Greet Example
>rails generate controller say hello

§It generates the code for the controller class named


“say” with a method named “hello”.
.
say_controller.rb

class SayController < ApplicationController


def hello
end
end
Greet Example
§ The same command also generated the code for the
view
app/views/say/hello.html.erb
§ Embedded Ruby
.
<!DOCTYPE html>
<!-- hello.html.erb - the template for the
greet application
-->
<html lang = "en">
<head>
<title> greet </title>
<meta charset = "utf-8" />
</head>
<body>
<h1> Hello from Rails </h1>
</body>
</html
Programming RoR: Examples
>rails new greet

.
Dynamic response of the application server
to a user request
http://localhost:3000/say/hello

0. Web Client->HTTP Get->Webrick->Rails->App

1. Instantiate SayController class

2. Call the hello action method

3. Search the views/say directory for hello.html.erb

4. Process hello.html.erb with Erb

5. Return the resulting hello.html to the


requesting browser
Greet Example Customization
<!DOCTYPE html>
<!-- hello.html.erb - the template for the
greet application
-->
<html lang = "en">
<head>
. <title> greet </title>
<meta charset = "utf-8" />
</head>
<body>
<h1> Hello from Rails </h1>
It is now <%= t = Time.now %> <br />
Number of seconds since midnight:
<%= t.hour * 3600 + t.min * 60 + t.sec %>
</body>
</html
.
RoR Web Application Development
A 4-tier Enterprise Example
Architecture of RoR Web Applications

Supporting Software
App User Interface WEBrick
(View) Web
User Interface
C
Application Logic L
Database Engine (Controller) I
or any E
Database Database API Web Server N
(Model:ORM) on the same T
system.
DBMS / Database Server RoR Web Applications

Architecture of RoR Web Applications


ORM (Object Relation Model)
§ We need to create a database for the enterprise
application.
§ The database is going to be relational. But we don’t
have to define the schema using DDL.
.
§ We will let Rails to do that for us.
§ Rails will create a class to specify the schema:
(1)The name of the class (object model) is the singular
of the relational table name.
(2)The name of the member variables are the names of
the columns of the table.
(3)The member methods of the class are inherited from
the ActiveRecord class.
ORM (Object Relation Model)
Here are the implementation steps:
(1) Create the application
>rails new cars
(2) Create the class to define the schema (cars/db/migrate)
.
>rails generate scaffold corvette
body_style:string miles:float year:integer
(3) Create the database table
>rake db:migrate
(4) The application, the controller, the view, are all automatically
created without writing a single line of Ruby code! (Familiar? PA3)
http://localhost:3000/corvettes
Programming RoR: Examples
http://localhost:3000/corvettes

.
Programming RoR: Examples
When clicking on “New corvette”

.
Programming RoR: Examples
After entering a “New corvette”

.
Programming RoR: Examples
UI for Editing

.
Programming RoR: Examples
For Destroy

.
Application

Recreate a web application using RoR in 5


minutes without writing a single line of code!
.
Summary

Database Programming as part of a multi-tier web application.


4-Tier Web Application
Server-side DB Programming Languages
DB Programming Patterns
PHP DB Programming API
JSP/Servlet DB Programming API
ADO.NET DB Programming API
RoR DB Programming
Summary

§ The lecture covered database integration in web applications,


emphasizing the four-tier architecture where databases serve as
the persistence layer.
§ Students learned about DBMSs like SQL Server and MySQL,
SQL programming, server-side programming with PHP, JSP,
ASP.NET, and Ruby on Rails, and ADO.NET data access
methods.
§ Concepts like transactions, data readers, data sets, data binding,
and object-relational mapping (ORM) were introduced.
§ Practical examples demonstrated connection management,
secure configuration, and GUI integration using controls like
DataGrids.
Review Questions
Q1: Compare and contrast DataReader and DataSet in
ADO.NET. When would you choose one over the other?

A1: DataReader is fast, forward-only, and read-only—


ideal for simple, sequential reads. DataSet is in-
memory, supports forward/backward traversal, and
allows updates—best for caching and complex
operations. Choose DataReader for performance-
critical reads; use DataSet when you need full data
manipulation or binding to UI components.
Review Questions
Q2: What are the core components of a four-tier web
application architecture, and where does the database
layer fit in?

A2: The components are:


(1) Client Interface (Browser)
(2) Web Server (HTTP Handler)
(3) Application Server (Business Logic)
(4) Database Server (Data Storage).
The database layer stores and retrieves data, interacting
with the application logic to serve dynamic content.
Review Questions
Q3: How does the ExecuteScalar() method differ from
ExecuteReader() and ExecuteNonQuery()? Provide
examples of each use case.

A3: ExecuteScalar() returns a single value (e.g., SELECT


COUNT(*)). ExecuteReader() returns a stream of rows (e.g.,
SELECT *). ExecuteNonQuery() executes DML commands
(e.g., INSERT, UPDATE, DELETE) and returns rows
affected. Use ExecuteScalar for aggregates,
ExecuteReader for queries, and ExecuteNonQuery for
modifications.
Review Questions
Q4: Why is exception handling crucial in database programming? Illustrate with
a code structure.

A4: Without exception handling, connection failures, invalid queries, or


transaction errors can crash applications. Structure:
try {
conn.Open();
// execute commands
} catch (SqlException ex) {
Console.WriteLine(ex.Message);
} finally {
conn.Close();
}
This ensures stability and resource management.
Review Questions
Q5: What is the role of web.config in ASP.NET applications,
and how does it enhance security and maintainability in
database programming?

A5: web.config stores configuration data like connection


strings. It separates code from configuration, enhances
maintainability (easy updates), and allows centralized
management of credentials without hardcoding, improving
security and deployment flexibility.
Review Questions
Q6: Describe how transactions are implemented in
ADO.NET. What is the importance of IsolationLevel?

A6: Transactions group commands into a unit that


succeeds or fails as one. Implemented using
B e g i n Tr a n s a c t i o n ( ) a n d C o m m i t ( ) o r R o l l b a c k ( ) .
IsolationLevel.Serializable prevents dirty reads and
ensures consistency by locking affected data until the
transaction completes.
Case Studies
Case Study 1:
An online bookstore wants to prevent inconsistencies
during simultaneous purchases.

Problem: How can transactions be implemented to ensure


data integrity?

Solution: Use BeginTransaction() and commit only after


inventory is updated and payment is confirmed. Rollback
on failure.
Case Studies
Case Study 2:
A university portal shows student results. It must fetch
results quickly and prevent server overload.

Problem: Which data access technique should be used?

Solution: Use SqlDataReader for fast, read-only access to


result sets. Bind data to grids or tables for display.
Case Studies
Case Study 3:
A web application requires dynamic content from multiple
tables joined on demand.

Problem: How can SQL and object-oriented programming


be leveraged?

Solution: Use INNER JOIN queries and encapsulate them


in command objects within PHP/JSP/ASP.NET using ORM
or direct SQL.
Case Studies
Case Study 4:
A developer hardcodes connection strings in ASP.NET.
Security breach exposes DB credentials.

Problem: How to avoid such vulnerabilities?

Solution: Store connection strings in web.config and


retrieve using
ConfigurationManager.AppSettings["connectString"].
Takeaways or Lessons Learnt
§ Databases are central to dynamic web applications, enabling
persistent, structured data management.
§ Multiple programming interfaces (PHP, JSP, ASP.NET) provide
flexibility in connecting and querying databases.
§ Secure coding practices like using config files and proper exception
handling are vital.
§ D i ff er ent dat a ac c es s me t h o d s s e r v e d i ff e r e n t p u r p o s e s :
DataReader for speed, DataSet for flexibility.
§ Transactions ensure atomicity, consistency, and rollback capabilities
for business-critical operations.
§ ORM and frameworks like Rails abstract schema creation,
accelerating development without sacrificing structure.
Exercises
Exercise 1:
Design an ASP.NET application that connects to a SQL
Server database using ADO.NET. It should allow users to
add, view, and delete books. Implement connection pooling
and ensure secure handling of connection strings.

Expected Output: Web form interface, web.config for


connection, SqlConnection, SqlCommand,
ExecuteNonQuery() for DML operations, and a DataGrid for
display.
Exercises
Exercise 2:
Develop a PHP application that retrieves and displays user
profiles from a MySQL database. The application must use
parameterized queries to prevent SQL injection and should
paginate results.

Expected Output: PHP script with PDO/MySQLi, prepare()


statements, bindParam(), and page navigation logic using
LIMIT and OFFSET.

You might also like