Visual Studio DB
Visual Studio DB
NET
Accessing SQL Server and MySQL from .NET and C#
3
Data Access Models
Connected Model
Connected data access model
constantly open
DB
DB
connection
5
Connected Model:
Benefits and Drawbacks
Connected data access model (SqlClient)
Benefits:
Concurrency control is easier to maintain
Better chance to work with the most recent
version of the data
Drawbacks:
Needs a constant reliable network
Problems when scalability is an issue
6
Disconnected Model
Disconnected data access model (DataSet)
temporary (offline)
connection DB
DB
9
ORM Model – Benefits
and Problems
ORM model benefits
Less flexibility
SQL is automatically generated
Performance issues (sometimes)
10
ADO.NET Architecture
What Is ADO.NET?
ADO.NET is a standard .NET class library for
accessing databases, processing data and XML
A program model for working with data in .NET
Supports connected, disconnected and ORM
data access models
Excellent integration with LINQ, XML and WCF
Allows executing SQL in RDBMS systems
DB connections, data readers, DB commands
Allows accessing data in the ORM approach
LINQ-to-SQL and ADO.NET Entity Framework 12
Namespaces In ADO.NET
System.Data
ADO.NET core classes
System.Data.Common
Common classes for all ADO.NET technologies
System.Data.Linq
LINQ-to-SQL framework classes
System.Data.Entity
Entity Framework classes
System.Xml
XML processing classes
13
Components of ADO.NET
Connected Model Disconn. Model LINQ-to-SQL Entity Framework
DataReader DataSet DataContext ObjectContext
DbCommand DataAdapter Table<T> EntityObject
…
SQL Server .NET OleDb .NET Oracle .NET ODBC .NET
Data Provider Data Provider Data Provider Data Provider
OLE DB sources
SQL Server 2005
(MS Access, MS Oracle ODBC Data
SQL Server 2008
Excel, Active Database Source
SQL Server 2012
Directory, etc.)
14
Data Providers In ADO.NET
Data Providersare collections of classes that
provide access to various databases
For different RDBMS systems different Data
Providers are available
Each provider uses vendor-specific protocols to talk
to the database server
Several common objects are defined:
Connection – to connect to the database
Command – to run an SQL command
DataReader – to retrieve data
15
Data Providers in ADO.NET (2)
Several standard ADO.NET Data Providers come
as part of .NET Framework
SqlClient – accessing SQL Server
OleDB – accessing standard OLE DB data sources
Odbc – accessing standard ODBC data sources
Oracle – accessing Oracle database
Third party Data Providers are available for:
MySQL, PostgreSQL, Interbase, DB2, SQLite
Other RDBMS systems and data sources
SQL Azure, Salesforce CRM, Amazon SimpleDB, …
16
Data Provider Classes
System.Data.SqlClient and
System.Data.SqlTypes
Data Provider classes for accessing SQL Server
System.Data.OleDb
AttachDbFilename=some_db.mdf
Attaches a local database file
Supported by SQL Express only
Server=server_name\database_instance
"." or "(local)" or "SOME_SERVER"
Database instance is "MSSQL", "SQLEXPRESS" or
other SQL Server instance name
Integrated Security – true / false
27
Connection Pooling
By default SqlClient
Data Provider uses
connection pooling for improved performance
Connection pooling works as follows:
When establishing a connection an existing one
is taken from the so called "connection pool"
If there is no free connection in the pool, a new
connection is established
When closing a connection it is returned to the
pool, instead of being closed
28
Working with SqlConnection
Explicitly opening and closing a connection
Open() and Close() methods
Works through the connection pool
DB connections are IDisposable objects
Always use the using construct in C#!
Implicitly opening and closing the connection
30
ADO.NET Classes for the
Connected Model
SqlDataReader XmlReader
SqlCommand
SqlConnection SqlParameter
Database
31
SqlClient and ADO.NET
Connected Model
Retrieving data in
connected model SqlDataReader
ExecuteScalar()
Returns a single value (the value in the first
column of the first row of the result set)
The returned value is System.Object but can be
casted to the actual returned data type
ExecuteReader()
Returns a SqlDataReader
It is a cursor over the returned records (result set)
CommandBehavior – assigns some options
34
The SqlCommand Class (3)
More important methods
ExecuteNonQuery()
Used for non-query SQL commands, e.g. INSERT
Returns the number of affected rows (int)
ExecuteXmlReader()
Returns the record set as XML
Returns an XmlReader
Supported in SqlClient Data Provider only
35
The SqlDataReader Class
SqlDataReader retrieves a sequence of records
(cursor) returned as result of an SQL command
Data is available for reading only (can't be changed)
Forward-only row processing (no move back)
Important properties and methods:
Read() – moves the cursor forward and returns
false if there is no next record
Item (indexer) – retrieves the value in the current
record by given column name or index
Close() – closes the cursor and releases resources
36
SqlCommand – Example
37
SqlDataReader – Example
SqlConnection dbCon = new SqlConnection … ;
dbCon.Open();
using(dbCon)
{
SqlCommand command = new SqlCommand(
"SELECT * FROM Employees", dbCon);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
string firstName = (string)reader["FirstName"];
string lastName = (string)reader["LastName"];
decimal salary = (decimal)reader["Salary"];
Console.WriteLine("{0} {1} - {2}",
firstName, lastName, salary);
}
}
}
38
Using SqlCommand and
SqlDataReader
Live Demo
SQL Injection
What is SQL Injection and How to Prevent It?
What is SQL Injection?
bool IsPasswordValid(string username, string password)
{
string sql =
"SELECT COUNT(*) FROM Users " +
"WHERE UserName = '" + username + "' and " +
"PasswordHash = '" + CalcSHA1(password) + "'";
SqlCommand cmd = new SqlCommand(sql, dbConnection);
int matchedUsersCount = (int) cmd.ExecuteScalar();
return matchedUsersCount > 0;
}
bool normalLogin =
IsPasswordValid("peter", "qwerty123"); // true
bool sqlInjectedLogin =
IsPasswordValid(" ' or 1=1 --", "qwerty123"); // true
bool evilHackerCreatesNewUser = IsPasswordValid(
"' INSERT INTO Users VALUES('hacker','') --", "qwerty123");
41
How Does
SQL Injection Work?
The following SQL commands are executed:
Usual password check (no SQL injection):
SELECT COUNT(*) FROM Users WHERE UserName = 'peter'
and PasswordHash = 'XOwXWxZePV5iyeE86Ejvb+rIG/8='
42
SQL
Injection
Live Demo
Preventing SQL Injection
Ways to prevent the SQL injection:
45
Parameterized
Commands – Example
private void InsertProject(string name, string description,
DateTime startDate, DateTime? endDate)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Projects " +
"(Name, Description, StartDate, EndDate) VALUES " +
"(@name, @desc, @start, @end)", dbCon);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@desc", description);
cmd.Parameters.AddWithValue("@start", startDate);
SqlParameter sqlParameterEndDate =
new SqlParameter("@end", endDate);
if (endDate == null)
sqlParameterEndDate.Value = DBNull.Value;
cmd.Parameters.Add(sqlParameterEndDate);
cmd.ExecuteNonQuery();
}
46
Primary Key Retrieval
Retrieval of an automatically generated
primary key is specific to each database server
In MS SQL Server IDENTITY column is used
Example of obtaining
the automatically
generated primary key in ADO.NET:
SqlCommand selectIdentityCommand =
new SqlCommand("SELECT @@Identity", dbCon);
int insertedRecordId = (int)
(decimal) selectIdentityCommand.ExecuteScalar();
47
Parameterized Queries
Live Demo
Connecting to Non-
Microsoft Databases
Connecting to Non-
Microsoft Databases
ADO.NET supports accessing various
databases via their Data Providers:
OLE DB – supported internally in ADO.NET
Access any OLE DB-compliant data source
E.g. MS Access, MS Excel, MS Project, MS
Exchange, Windows Active Directory, text files
Oracle – supported internally in ADO.NET
MySQL – third party extension
PostgreSQL – third party extension
50
ADO.NET Data Interfaces
ADO.NET Data Providers implement the
following interfaces:
IDbConnection
IDbCommand, IDataParameter
IDataReader
IDbDataAdapter
51
ADO.NET Base Classes
ADO.NET provides the following base classes:
DbConnection
DbCommand / DbParameter
DbDataReader
DbTransaction
DbParameterCollection
DbDataAdapter
DbCommandBuilder
DbConnectionStringBuilder
DBDataPermission
52
OLE DB Data Provider
OleDbConnection – establishes a connection to
an OLE DB source of data
OleDbConnection dbConn = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\MyDB.mdb;Persist Security Info=False");
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=
C:\Library.mdb;Persist Security Info=False
54
Connecting to MS
Access Database
Live Demo
Connecting to MySQL
Accessing MySQL from ADO.NET
Connecting to MySQL from C#
Download and install MySQL Connector/Net
http://dev.mysql.com/downloads/connector/net/
Add reference to MySQL.Data.dll
MySqlConnection dbConnection =
new MySqlConnection("Server=localhost; Port=3306;
Database=world; Uid=root; Pwd=root; pooling=true");
57
Connecting to MySQL
Live Demo
Working with
Dates and Images
Best Practices
Working with Dates:
Best Practices
Use the date-specific types in the database
and never varchar / nvarchar
61
Working with Dates – Example
CREATE TABLE Messages
(
MsgId int identity not null primary key,
MsgText nvarchar(1000),
MsgDate datetime –- Don’t use varchar for dates!
)
62
Working With Dates
Live Demo
Storing Images in the DB
Store images in the file system or in the DB?
Questions?
Exercises
1. Write a program that retrieves from the Northwind
sample database in MS SQL Server the number of
rows in the Categories table.
2. Write a program that retrieves the name and
description of all categories in the Northwind DB.
3. Write a program that retrieves from the Northwind
database all product categories and the names of
the products in each category. Can you do this with a
single SQL query (with table join)?
4. Write a method that adds a new product in the
products table in the Northwind database. Use a
parameterized SQL command.
Exercises (2)
5. Write a program that retrieves the images for all
categories in the Northwind database and stores
them as JPG files in the file system.
6. Create an Excel file with 2 columns: name and score: